Files
zyt/server/app/common/service/tcm/PrescriptionAuditSignature.php
T
2026-11-14 15:19:59 +08:00

92 lines
3.7 KiB
PHP

<?php
declare(strict_types=1);
namespace app\common\service\tcm;
use DomainException;
/** Bounded, visible PNG handwriting; identity is supplied by the authenticated auditor. */
final class PrescriptionAuditSignature
{
public const MAX_BYTES = 262144;
public const MAX_DATA_URL_LENGTH = 349550;
public static function normalize(mixed $value): string
{
if (!is_string($value) || trim($value) === '') {
throw new DomainException('请先完成审核签名');
}
if (strlen($value) > self::MAX_DATA_URL_LENGTH) {
throw new DomainException('审核签名图片过大,请清空后重新签名');
}
if (!str_starts_with($value, 'data:image/png;base64,')) {
throw new DomainException('审核签名必须是有效的 PNG 图片');
}
$encoded = substr($value, 22);
if ($encoded === '' || preg_match('/^[A-Za-z0-9+\/]+={0,2}$/D', $encoded) !== 1) {
throw new DomainException('审核签名图片格式无效');
}
$bytes = base64_decode($encoded, true);
if ($bytes === false || strlen($bytes) > self::MAX_BYTES
|| !str_starts_with($bytes, "\x89PNG\r\n\x1a\n")) {
throw new DomainException('审核签名图片格式无效或过大');
}
$size = @getimagesizefromstring($bytes);
if ($size === false || ($size[2] ?? 0) !== IMAGETYPE_PNG
|| $size[0] < 4 || $size[1] < 4 || $size[0] > 2048 || $size[1] > 2048
|| $size[0] * $size[1] > 2097152) {
throw new DomainException('审核签名图片尺寸无效');
}
if (!function_exists('imagecreatefromstring')) {
throw new DomainException('签名校验服务未配置,请联系管理员');
}
$image = @imagecreatefromstring($bytes);
if ($image === false) {
throw new DomainException('审核签名图片无法读取');
}
try {
$ink = 0;
$minX = $size[0];
$minY = $size[1];
$maxX = $maxY = -1;
for ($y = 0; $y < $size[1]; $y++) {
for ($x = 0; $x < $size[0]; $x++) {
$rgba = imagecolorsforindex($image, imagecolorat($image, $x, $y));
// Composite against the white signature sheet so transparent RGB is not ink.
$opacity = (127 - $rgba['alpha']) / 127;
$darkness = (255 - min($rgba['red'], $rgba['green'], $rgba['blue'])) * $opacity;
if ($darkness < 32) {
continue;
}
$ink++;
$minX = min($minX, $x);
$minY = min($minY, $y);
$maxX = max($maxX, $x);
$maxY = max($maxY, $y);
}
}
if ($ink < 12 || $ink >= $size[0] * $size[1] * 0.95
|| max($maxX - $minX, $maxY - $minY) < 3) {
throw new DomainException('签名不能为空白,请在签名框内手写签名');
}
// Decode/re-encode strips unrelated PNG metadata and any appended payload.
imagesavealpha($image, true);
ob_start();
try {
$ok = imagepng($image);
$normalized = (string) ob_get_contents();
} finally {
ob_end_clean();
}
if (!$ok || strlen($normalized) > self::MAX_BYTES) {
throw new DomainException('审核签名图片过大,请清空后重新签名');
}
return 'data:image/png;base64,' . base64_encode($normalized);
} finally {
imagedestroy($image);
}
}
}