Posted By

jamesming on 03/07/09


Tagged

barcode


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

wizard04
Scooter
muoto


PHP output UPC-A 11-digit barcodes


 / Published in: PHP
 

URL: http://www.barcodeisland.com

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

Report this snippet  

You need to login to post a comment.