UPC-A 是北美通用商品條碼標準,共 12 位數字(含 1 位檢查碼)。本文提供純 PHP GD 實作,無需外部庫,可直接輸出 PNG 圖片供列印或網頁顯示。
<?php
function UPCAbarcode($code) {
// 參數驗證:必須 11 位數字(不含檢查碼)
if (strlen($code) !== 11 || !ctype_digit($code)) {
die("UPC-A 需 11 位數字參數");
}
// 編碼表:左半邊 (L) 與右半邊 (R) 不同
$Lencode = ['0001101','0011001','0010011','0111101','0100011',
'0110001','0101111','0111011','0110111','0001011'];
$Rencode = ['1110010','1100110','1101100','1000010','1011100',
'1001110','1010000','1000100','1001000','1110100'];
$ends = '101'; // 起始/結束護衛條
$center = '01010'; // 中間分隔條
// 計算檢查碼 (EAN-13 算法)
$ncode = '0' . $code; // UPC-A 視為 EAN-13 前綴 0
$even = $odd = 0;
for ($x = 0; $x < 12; $x++) {
($x % 2 === 0) ? $even += $ncode[$x] : $odd += $ncode[$x];
}
$check = (10 - (($odd * 3 + $even) % 10)) % 10;
$code .= $check; // 現在為 12 位
// 組合條碼二進位字串
$bars = $ends . $Lencode[$code[0]];
for ($x = 1; $x < 6; $x++) $bars .= $Lencode[$code[$x]];
$bars .= $center;
for ($x = 6; $x < 12; $x++) $bars .= $Rencode[$code[$x]];
$bars .= $ends; // 總長 95 模組
// 繪圖參數
$lw = 2; // 模組寬度 (px)
$hi = 100; // 條碼高度 (px)
$img = imagecreate($lw * 95 + 30, $hi + 30);
$fg = imagecolorallocate($img, 0, 0, 0);
$bg = imagecolorallocate($img, 255, 255, 255);
imagefilledrectangle($img, 0, 0, $lw * 95 + 30, $hi + 30, $bg);
// 繪製條碼
$shift = 10;
for ($x = 0; $x < strlen($bars); $x++) {
// 護衛條與中間分隔條加高
if ($x < 10 || ($x >= 45 && $x < 50) || $x >= 85) $sh = 10; else $sh = 0;
$color = ($bars[$x] === '1') ? $fg : $bg;
imagefilledrectangle($img,
($x * $lw) + 15, 5,
($x + 1) * $lw + 14, $hi + 5 + $sh,
$color
);
}
// 繪製人工可讀數字
$font = 5;
imagestring($img, 4, 5, $hi - 5, $code[0], $fg); // 首位左側
for ($x = 0; $x < 5; $x++) {
imagestring($img, $font, $lw * (13 + $x * 6) + 15, $hi + 5, $code[$x + 1], $fg);
imagestring($img, $font, $lw * (53 + $x * 6) + 15, $hi + 5, $code[$x + 6], $fg);
}
imagestring($img, 4, $lw * 95 + 17, $hi - 5, $code[11], $fg); // 末位右側
// 輸出
header('Content-Type: image/png');
imagepng($img);
imagedestroy($img);
}
// 使用範例
UPCAbarcode('13322483157'); // 11 位數字
?>
| 步驟 | 說明 |
|---|---|
| 檢查碼計算 | UPC-A 視為 EAN-13 前綴 0,奇位權重 3、偶位權重 1,總和模 10 補足 |
| 左右編碼不同 | 左半邊用 L-code(奇偶校驗用),右半邊用 R-code(L-code 反相+互補) |
| 護衛條加高 | 起始/中間/結束護衛條比資料條高,便於掃描器定位 |
| 靜區 | 左右各留 9-11 模組空白 (程式中 +30px 左右邊距) |
picqer/php-barcode-generator 或 bacon/bacon-qr-code。<rect>,可無限縮放不失真。需啟用 php-gd 擴展(Ubuntu: apt install php-gd,Windows: 取消註解 extension=gd)。