Barcode.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace core\util;
  3. require_once('barcode/class/BCGFontFile.php');
  4. require_once('barcode/class/BCGColor.php');
  5. require_once('barcode/class/BCGDrawing.php');
  6. require_once('barcode/class/BCGcode128.barcode.php');
  7. class Barcode{
  8. public $size; //字体大小
  9. private $color_black;
  10. private $color_white;
  11. private $font;
  12. public $drawException = null;
  13. public $fontPath;
  14. public $content;
  15. public function __construct($size,$content){
  16. $this->color_black = new \BCGColor(0, 0, 0);
  17. $this->color_white = new \BCGColor(255, 255, 255);
  18. $this->size = $size;
  19. $this->fontPath = str_replace("\\", "/", root_path() . "core/util/barcode/font/Arial.ttf");
  20. $this->font = new \BCGFontFile($this->fontPath, $this->size);
  21. $this->content = $content;
  22. }
  23. //生成条形码
  24. public function generateBarcode($path='', $scale = 2){
  25. try {
  26. $code = new \BCGcode128();
  27. $code->setScale($scale);
  28. $code->setThickness(30); // 条形码的厚度
  29. $code->setForegroundColor($this->color_black); // 条形码颜色
  30. $code->setBackgroundColor($this->color_white); // 空白间隙颜色
  31. $code->setFont($this->font); //
  32. $code->parse($this->content); // 条形码需要的数据内容
  33. } catch(Exception $exception) {
  34. $this->drawException = $exception;
  35. }
  36. if($path == ''){
  37. $path = 'upload/barcode';//条形码存放路径
  38. }
  39. if (! is_dir($path)) {
  40. $mode = intval('0777', 8);
  41. mkdir($path, $mode, true);
  42. chmod($path, $mode);
  43. }
  44. $path = $path . '/' . $this->content . '.png';
  45. if (file_exists($path)) {
  46. unlink($path);
  47. }
  48. //根据以上条件绘制条形码
  49. $drawing = new \BCGDrawing('', $this->color_white);
  50. if($this->drawException) {
  51. $drawing->drawException($this->drawException);
  52. } else {
  53. $drawing->setBarcode($code);
  54. $drawing->setFilename($path);
  55. $drawing->draw();
  56. }
  57. // 生成PNG格式的图片
  58. $drawing->finish(\BCGDrawing::IMG_FORMAT_PNG);
  59. return $path;
  60. }
  61. }
  62. ?>