下载barcodegen扩展库
下载链接https://www.barcodebakery.com/en/download
我用的v5.2.1
将扩展包解压至vendor目录下
service方法封装
public function createCode($text,$type)
{
$class_dir = VENDOR_PATH . 'barcodegen/class/';
// Including all required classes
require_once($class_dir . 'BCGColor.php');
require_once($class_dir . 'BCGDrawing.php');
require_once($class_dir . 'BCGcode128.barcode.php');
require_once($class_dir . 'BCGean13.barcode.php');
require_once($class_dir . 'BCGFontFile.php');
// Loading Font
// 注意font和class是同一级文件夹
$font = new \BCGFontFile(VENDOR_PATH . 'barcodegen/class/font/Arial.ttf', 13);// The arguments are R, G, B for color.
$color_black = new \BCGColor(0, 0, 0);
$color_white = new \BCGColor(255, 255, 255);
// $text = 'hello';
$drawException = null;
try {
$code = $type == 1 ? new \BCGcode128() : new \BCGean13();
$code->setScale(2); // Resolution
$code->setThickness(30); // Thickness
$code->setForegroundColor($color_black); // Color of bars
$code->setBackgroundColor($color_white); // Color of spaces
$code->setFont($font); // Font (or 0) 0不显示文字
$code->parse($text); // Text
} catch (Exception $exception) {
$drawException = $exception;
}
$filename = '';
//路径是否存在
$drawing = new \BCGDrawing($filename, $color_white);//filename为空直接输出至页面
if ($drawException) {
$drawing->drawException($drawException);
} else {
$drawing->setBarcode($code);
$drawing->draw();
}
header('Content-Type: image/png');
header('Content-Disposition: inline; filename="barcode.png"');
$drawing->finish(\BCGDrawing::IMG_FORMAT_PNG);
}
控制器调用
/**
* @throws \BCGArgumentException
* @throws \BCGDrawException
*/
public function createBarcode()
{
$goods_sn = input('goods_sn');
!preg_match("/^\d{13}$/",$goods_sn) ? $this->error('商品编号不符合规则') : '';
$info = \app\common\model\Goods::where("goodsn",$goods_sn)->find();
empty($info) ? $this->error('该商品不存在') : '';
$barcode = new Barcodegen();
$barcode->createCode($goods_sn,$info['bar_code_switch']);
}