简述:
使用php的GD库可以将图片转换为黑白图片,利用的内置函数有:
- getimagesize:获取图片的信息,包括宽高、mime类型等信息;
- imagecolorat:获取图片每个位置的RGB值
- imagecolorallocate:为图片分配颜色
- imagesetpixel:在图片的指定坐标处绘制像素
完整代码:
/**
* 转黑白图片
* @param string $sourceImg 要转换的图片路径
* @param string $filePath 最终保存的图片路径
* @return [type] [description]
*/
function createImg($sourceImg,$filePath) {
list($width, $height, $type, $attr) = getimagesize($sourceImg);
$imageinfo = array(
'width' => $width,
'height' => $height,
'type' => image_type_to_extension($type, false),
'attr' => $attr,
);
$fun = "imagecreatefrom" . $imageinfo['type'];
$image = $fun($sourceImg);
$img_width = $width;
$img_height = $height;
for($i=0;$i<$img_height;$i++){
for($k=0;$k<$img_width;$k++){
// 获取图片每个位置的RGB值
$gray = (imagecolorat($image,$k,$i)>>8)&0xFF;
// 在指定坐标处绘制像素
imagesetpixel($image, $k, $i, imagecolorallocate($image, $gray,$gray,$gray));
}
}
$funcs = "image" . $imageinfo['type'];
// 保存图片
// 注意第三个参数为压缩级别,从0~9
$res = $funcs($image, $filePath, 6);
imagedestroy($image);
return $res;
}