PHP生成条形码实现程序

条形码(barcode)是将宽度不等的多个黑条和空白,按照一定的编码规则排列,用以表达一组信息的图形标识符,常见的条形码是由反射率相差很大的黑条(简称条)和白条(简称空)排成平行线的图案对于上面有个大概的了解后,下面我们可以重新整合下代码,更加方便的使用它,代码如下:

  1. function UPCAbarcode($code)
  2. {
  3. $lw = 2; $hi = 100;
  4. $Lencode = array('0001101','0011001','0010011','0111101','0100011',
  5. '0110001','0101111','0111011','0110111','0001011');
  6. $Rencode = array('1110010','1100110','1101100','1000010','1011100',
  7. '1001110','1010000','1000100','1001000','1110100');
  8. $ends = '101'; $center = '01010';
  9. /* UPC-A Must be 11 digits, we compute the checksum. */
  10. if ( strlen($code) != 11 ) { die("UPC-A Must be 11 digits."); }
  11. /* Compute the EAN-13 Checksum digit */
  12. $ncode = '0'.$code;
  13. $even = 0; $odd = 0;
  14. for ($x=0;$x<12;$x++)
  15. {
  16. if ($x % 2) { $odd += $ncode[$x]; } else { $even += $ncode[$x]; }
  17. }
  18. $code.=(10 - (($odd * 3 + $even) % 10)) % 10;
  19. /* Create the bar encoding using a binary string */
  20. $bars=$ends;
  21. $bars.=$Lencode[$code[0]];
  22. for($x=1;$x<6;$x++)
  23. {
  24. $bars.=$Lencode[$code[$x]];
  25. }
  26. $bars.=$center;
  27. for($x=6;$x<12;$x++)
  28. {
  29. $bars.=$Rencode[$code[$x]];
  30. }
  31. $bars.=$ends;
  32. /* Generate the Barcode Image */
  33. $img = ImageCreate($lw*95+30,$hi+30);
  34. $fg = ImageColorAllocate($img, 0, 0, 0);
  35. $bg = ImageColorAllocate($img, 255, 255, 255);
  36. ImageFilledRectangle($img, 0, 0, $lw*95+30, $hi+30, $bg);
  37. $shift=10;
  38. for ($x=0;$x<strlen($bars);$x++)
  39. {
  40. if (($x<10) || ($x>=45 && $x<50) || ($x >=85)) { $sh=10; } else { $sh=0; }
  41. if ($bars[$x] == '1') { $color = $fg; } else { $color = $bg; }
  42. ImageFilledRectangle($img, ($x*$lw)+15,5,($x+1)*$lw+14,$hi+5+$sh,$color);
  43. }
  44. /* Add the Human Readable Label */
  45. ImageString($img,4,5,$hi-5,$code[0],$fg);
  46. for ($x=0;$x<5;$x++)
  47. {
  48. ImageString($img,5,$lw*(13+$x*6)+15,$hi+5,$code[$x+1],$fg);
  49. ImageString($img,5,$lw*(53+$x*6)+15,$hi+5,$code[$x+6],$fg);
  50. }
  51. ImageString($img,4,$lw*95+17,$hi-5,$code[11],$fg);
  52. /* Output the Header and Content. */
  53. header("Content-Type: image/png");
  54. ImagePNG($img);
  55. }
  56. UPCAbarcode('13322483157');
  57. ?>