最近有个项目里面有企业公章,是透明底的图片,直径256,但是通常我们做的功能是限制上传图片,可是这样无法保证用户上传的公章是256的,在做PDF合同时嵌入的公章也就会出现偏小的情况,为此,特意对上传的图片进行裁剪,提取公章从新存储,代码如下。
function average($imgurl='')
{
$imgurl = getcwd().$imgurl;
$img = imagecreatefromstring(file_get_contents($imgurl));
$w = imagesx($img);
$h = imagesy($img);
$minx = $miny = $maxx = $maxy = 0;
for($y = 0; $y < $h; $y++) {
for($x = 0; $x < $w; $x++) {
$r = $g = $b = 0;
$rgb = ImageColorAt($img, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
if($r>=200&&$g<=80&&$b<=80)
{
$minx = !empty($minx)&&$minx<$x?$minx:$x;
$miny = !empty($miny)&&$miny<$y?$miny:$y;
$maxx = $maxx<$x?$x:$maxx;
$maxy = $maxy<$y?$y:$maxy;
}
}
}
$img_width = $img_height = 256;
if (function_exists('imagecreatetruecolor'))
{
$im = imagecreatetruecolor($img_width, $img_height);
}
else
{
$im = imagecreate($img_width, $img_height);
}
$bg_color = imagecolorallocate($im, 255, 255, 255);
imagecolortransparent($im,$bg_color);
ImageFilledRectangle($im, 0, 0, $img_width, $img_height, $bg_color);
$w = $maxx-$minx;
$h = $maxy-$miny;
$l = $w>$y?$w:$h;
$l = $l+2;
imagecopyresampled($im,$img,0,0,$minx-1,$miny-1,$img_width,$img_height,$l,$l);
imagepng($im, $imgurl);
ImageDestroy($im);
}
这里最主要的函数ImageColorAt,判断色值,其中判断的部分来自官方手册。只不过加了对应的数值的判断。上述代码理论上还可以提取文字等简单色彩图像。