本文目录导读:

我来为您提供一个完整的PHP条形码生成和扫码处理解决方案:
条形码生成方案
使用 Zend\Barcode(推荐)
<?php
// 安装: composer require zendframework/zend-barcode
require_once 'vendor/autoload.php';
use Zend\Barcode\Barcode;
class BarcodeGenerator {
/**
* 生成条形码
* @param string $data 条形码数据
* @param string $type 类型:code128, code39, ean13等
* @param array $options 配置选项
*/
public function generateBarcode($data, $type = 'code128', $options = []) {
$defaultOptions = [
'barHeight' => 50,
'drawText' => true,
'factor' => 2, // 缩放比例
'fontSize' => 12,
];
$options = array_merge($defaultOptions, $options);
// 生成条形码
$barcodeOptions = [
'text' => $data,
'barHeight' => $options['barHeight'],
'factor' => $options['factor'],
'drawText' => $options['drawText'],
];
$rendererOptions = [
'imageType' => 'png',
'horizontalPosition' => 'center',
'verticalPosition' => 'middle',
];
// 生成图片
$imageResource = Barcode::factory(
$type,
'image',
$barcodeOptions,
$rendererOptions
)->draw();
return $imageResource;
}
/**
* 保存条形码到文件
*/
public function saveBarcode($data, $filename, $type = 'code128') {
$image = $this->generateBarcode($data, $type);
// 保存为PNG文件
imagepng($image, $filename);
imagedestroy($image);
return $filename;
}
/**
* 输出条形码到浏览器
*/
public function outputBarcode($data, $type = 'code128') {
header('Content-Type: image/png');
$image = $this->generateBarcode($data, $type);
imagepng($image);
imagedestroy($image);
}
}
?>
使用 php-barcode-generator
<?php
// 安装: composer require picqer/php-barcode-generator
require_once 'vendor/autoload.php';
use Picqer\Barcode\BarcodeGeneratorPNG;
class SimpleBarcodeGenerator {
public function generate($data, $type = 'C128') {
$generator = new BarcodeGeneratorPNG();
// 支持的条形码类型
$types = [
'C39' => BarcodeGeneratorPNG::TYPE_CODE_39,
'C128' => BarcodeGeneratorPNG::TYPE_CODE_128,
'EAN13' => BarcodeGeneratorPNG::TYPE_EAN_13,
'EAN8' => BarcodeGeneratorPNG::TYPE_EAN_8,
'UPCA' => BarcodeGeneratorPNG::TYPE_UPC_A,
'UPCB' => BarcodeGeneratorPNG::TYPE_UPC_B,
];
$barcodeType = isset($types[$type]) ? $types[$type] : BarcodeGeneratorPNG::TYPE_CODE_128;
// 生成条形码
return $generator->getBarcode($data, $barcodeType, 2, 50);
}
public function saveToFile($data, $filename, $type = 'C128') {
$barcode = $this->generate($data, $type);
file_put_contents($filename, $barcode);
return $filename;
}
}
?>
条形码读取/扫码处理
使用 Zxing(跨平台)
<?php
// 使用Java的zxing库通过命令行或API调用
class BarcodeReader {
/**
* 读取本地图片中的条形码
*/
public function readBarcodeFromImage($imagePath) {
// 方案1: 使用PHP的exec调用Java程序
$command = "java -cp zxing-core.jar:zxing-javase.jar " .
"com.google.zxing.client.j2se.CommandLineRunner " .
escapeshellarg($imagePath) . " --output_format=text";
$output = shell_exec($command);
return $output;
}
}
?>
使用 PHP 的图像处理
<?php
class ImageBarcodeReader {
/**
* 简单的二维码/条形码识别
*/
public function detectBarcode($imagePath) {
// 检查GD库
if (!extension_loaded('gd')) {
throw new Exception("GD Library not loaded");
}
// 读取图像
$image = imagecreatefromstring(file_get_contents($imagePath));
// 转换为灰度
$width = imagesx($image);
$height = imagesy($image);
// 基本图像处理用于条形码检测
$grayscale = imagecreatetruecolor($width, $height);
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
$rgb = imagecolorat($image, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$gray = (int)($r * 0.299 + $g * 0.587 + $b * 0.114);
imagesetpixel($grayscale, $x, $y, imagecolorallocate($grayscale, $gray, $gray, $gray));
}
}
return $grayscale;
}
}
?>
Web扫码处理
<?php
class BarcodeScannerController {
/**
* 处理上传的条形码图片
*/
public function handleUpload() {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_FILES['barcode_image'])) {
$file = $_FILES['barcode_image'];
// 验证文件
if ($file['error'] !== UPLOAD_ERR_OK) {
return ['error' => '上传失败'];
}
$allowedTypes = ['image/png', 'image/jpeg', 'image/gif'];
if (!in_array($file['type'], $allowedTypes)) {
return ['error' => '不支持的图片类型'];
}
// 保存临时文件
$tmpPath = 'uploads/' . uniqid() . '.' .
pathinfo($file['name'], PATHINFO_EXTENSION);
if (move_uploaded_file($file['tmp_name'], $tmpPath)) {
// 扫描条形码
$result = $this->readBarcode($tmpPath);
// 清理
unlink($tmpPath);
return [
'success' => true,
'barcode' => $result
];
}
}
}
return ['error' => '无效的请求'];
}
/**
* 处理摄像头扫码(前端WebSocket或WebRTC)
*/
public function handleScannerData() {
// 获取前端传递的扫码数据
$data = json_decode(file_get_contents('php://input'), true);
if (isset($data['barcode'])) {
return [
'success' => true,
'data' => $data['barcode'],
'time' => date('Y-m-d H:i:s')
];
}
return ['error' => '扫描失败'];
}
}
?>
完整示例代码
<?php
// 安装依赖后使用
require_once 'vendor/autoload.php';
use Picqer\Barcode\BarcodeGeneratorPNG;
use Picqer\Barcode\BarcodeGeneratorHTML;
class BarcodeManager {
private $db;
public function __construct($db) {
$this->db = $db;
}
/**
* 商品条形码管理
*/
public function generateProductBarcode($productId) {
// 获取商品信息
$product = $this->db->query("SELECT * FROM products WHERE id = $productId")->fetch();
if (!$product) {
throw new Exception("商品不存在");
}
// 生成条形码数据(可以是商品编号等)
$barcodeData = $product['code'];
// 生成PNG条形码
$generator = new BarcodeGeneratorPNG();
$barcodeContent = $generator->getBarcode($barcodeData, BarcodeGeneratorPNG::TYPE_CODE_128);
// 保存到文件
$filename = 'barcodes/' . $barcodeData . '.png';
file_put_contents($filename, $barcodeContent);
// 保存到数据库
$this->db->exec("UPDATE products SET barcode_path = '$filename' WHERE id = $productId");
return $filename;
}
/**
* 批量生成条形码
*/
public function generateBulk($productIds) {
$results = [];
foreach ($productIds as $id) {
try {
$filename = $this->generateProductBarcode($id);
$results[] = [
'product_id' => $id,
'success' => true,
'barcode' => $filename
];
} catch (Exception $e) {
$results[] = [
'product_id' => $id,
'success' => false,
'error' => $e->getMessage()
];
}
}
return $results;
}
/**
* 扫描入口处理
*/
public function scanBarcode($barcodeValue) {
// 查找商品
$product = $this->db->query(
"SELECT * FROM products WHERE code = '$barcodeValue'"
)->fetch();
if (!$product) {
return ['error' => '未找到商品'];
}
// 记录扫描日志
$this->db->exec(
"INSERT INTO scan_logs (barcode, product_id, scan_time)
VALUES ('$barcodeValue', {$product['id']}, NOW())"
);
return [
'success' => true,
'product' => $product
];
}
}
?>
前端扫码功能集成
<!DOCTYPE html>
<html>
<head>扫码系统</title>
<!-- 引入ZXing JS库 -->
<script src="https://cdn.jsdelivr.net/npm/@zxing/library@0.18.6/umd/index.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
</head>
<body>
<!-- 摄像头扫码区域 -->
<div id="scanner" style="width: 640px; height: 480px;"></div>
<!-- 上传图片扫码 -->
<input type="file" id="barcodeImage" accept="image/*">
<script>
// 使用ZXing进行扫码
const codeReader = new ZXing.BrowserMultiFormatReader();
function initScanner() {
codeReader.decodeFromVideoDevice(
null,
'scanner',
(result, err) => {
if (result) {
handleBarcodeResult(result.getText());
}
if (err && !(err instanceof ZXing.NotFoundException)) {
console.error(err);
}
}
);
}
function handleBarcodeResult(barcode) {
// 发送到服务器处理
$.ajax({
url: '/scan_process.php',
method: 'POST',
data: { barcode: barcode },
success: function(response) {
console.log('扫码结果:', response);
}
});
}
// 处理上传图片
$('#barcodeImage').on('change', function(e) {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(event) {
const img = new Image();
img.onload = function() {
codeReader.decodeFromImage(img)
.then(result => {
handleBarcodeResult(result.getText());
})
.catch(err => {
console.error('扫码失败:', err);
});
};
img.src = event.target.result;
};
reader.readAsDataURL(file);
});
// 初始化扫码
$(document).ready(function() {
initScanner();
});
</script>
</body>
</html>
这个解决方案提供了完整的条形码生成、读取、扫码处理功能,根据您的具体需求,可以选择合适的组件或组合使用,生产环境中建议使用成熟的库(如zxing、quaggaJS)来处理复杂的条码识别场景。