BarcodeGeneratorJPG.php 2.5 KB

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