cli-barcode PHP
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

74 regels
2.8 KiB

  1. <?php
  2. namespace Picqer\Barcode;
  3. class BarcodeGeneratorPNG extends BarcodeGenerator
  4. {
  5. /**
  6. * Return a PNG image representation of barcode (requires GD or Imagick library).
  7. *
  8. * @param string $code code to print
  9. * @param string $type type of barcode:
  10. * @param int $widthFactor Width of a single bar element in pixels.
  11. * @param int $totalHeight Height of a single bar element in pixels.
  12. * @param array $color RGB (0-255) foreground color for bar elements (background is transparent).
  13. * @return string image data or false in case of error.
  14. * @public
  15. */
  16. public function getBarcode($code, $type, $widthFactor = 2, $totalHeight = 30, $color = array(0, 0, 0))
  17. {
  18. $barcodeData = $this->getBarcodeData($code, $type);
  19. // calculate image size
  20. $width = ($barcodeData['maxWidth'] * $widthFactor);
  21. $height = $totalHeight;
  22. if (function_exists('imagecreate')) {
  23. // GD library
  24. $imagick = false;
  25. $png = imagecreate($width, $height);
  26. $colorBackground = imagecolorallocate($png, 255, 255, 255);
  27. imagecolortransparent($png, $colorBackground);
  28. $colorForeground = imagecolorallocate($png, $color[0], $color[1], $color[2]);
  29. } elseif (extension_loaded('imagick')) {
  30. $imagick = true;
  31. $colorForeground = new \imagickpixel('rgb(' . $color[0] . ',' . $color[1] . ',' . $color[2] . ')');
  32. $png = new \Imagick();
  33. $png->newImage($width, $height, 'none', 'png');
  34. $imageMagickObject = new \imagickdraw();
  35. $imageMagickObject->setfillcolor($colorForeground);
  36. } else {
  37. return false;
  38. }
  39. // print bars
  40. $positionHorizontal = 0;
  41. foreach ($barcodeData['bars'] as $bar) {
  42. $bw = round(($bar['width'] * $widthFactor), 3);
  43. $bh = round(($bar['height'] * $totalHeight / $barcodeData['maxHeight']), 3);
  44. if ($bar['drawBar']) {
  45. $y = round(($bar['positionVertical'] * $totalHeight / $barcodeData['maxHeight']), 3);
  46. // draw a vertical bar
  47. if ($imagick) {
  48. $imageMagickObject->rectangle($positionHorizontal, $y, ($positionHorizontal + $bw), ($y + $bh));
  49. } else {
  50. imagefilledrectangle($png, $positionHorizontal, $y, ($positionHorizontal + $bw) - 1, ($y + $bh),
  51. $colorForeground);
  52. }
  53. }
  54. $positionHorizontal += $bw;
  55. }
  56. ob_start();
  57. if ($imagick) {
  58. $png->drawimage($imageMagickObject);
  59. echo $png;
  60. } else {
  61. imagepng($png);
  62. imagedestroy($png);
  63. }
  64. $image = ob_get_clean();
  65. return $image;
  66. }
  67. }