【发布时间】:2011-11-23 15:43:59
【问题描述】:
我有一个脚本可以上传图片并调整其大小,一切正常,但我希望能够从图像中去除颜色,使其变成黑白(本质上是各种灰色阴影)。我不确定如何实现这一目标?
谢谢
【问题讨论】:
标签: image-processing
我有一个脚本可以上传图片并调整其大小,一切正常,但我希望能够从图像中去除颜色,使其变成黑白(本质上是各种灰色阴影)。我不确定如何实现这一目标?
谢谢
【问题讨论】:
标签: image-processing
尝试以下方法:
<?php
$source_file = "test_image.jpg";
$im = ImageCreateFromJpeg($source_file);
$imgw = imagesx($im);
$imgh = imagesy($im);
for ($i=0; $i<$imgw; $i++)
{
for ($j=0; $j<$imgh; $j++)
{
// get the rgb value for current pixel
$rgb = ImageColorAt($im, $i, $j);
// extract each value for r, g, b
$rr = ($rgb >> 16) & 0xFF;
$gg = ($rgb >> 8) & 0xFF;
$bb = $rgb & 0xFF;
// get the Value from the RGB value
$g = round(($rr + $gg + $bb) / 3);
// grayscale values have r=g=b=g
$val = imagecolorallocate($im, $g, $g, $g);
// set the gray value
imagesetpixel ($im, $i, $j, $val);
}
}
header('Content-type: image/jpeg');
imagejpeg($im);
?>
请注意,我从this article 中无耻地撕掉了这个 sn-p,我使用谷歌搜索找到了这个词:php convert image to grayscale
[编辑] 从 cmets 中,如果你使用 PHP5,你也可以使用:
imagefilter($im, IMG_FILTER_GRAYSCALE);
【讨论】:
imagefilter,它只适用于 PHP5,我假设(并希望)这个使用更复杂的方法。
最简单的解决方案是使用 imagefilter($im, IMG_FILTER_GRAYSCALE); 但是这里提到的每一种方法都不是 100% 有效的。所有这些都依赖图像的调色板,但可能会丢失灰色阴影,并使用调色板中的另一种颜色。
我的解决方案是使用 imagecolorset 替换调色板中的颜色。
$colorsCount = imagecolorstotal($img->getImageResource());
for($i=0;$i<$colorsCount;$i++){
$colors = imagecolorsforindex( $img->getImageResource() , $i );
$g = round(($colors['red'] + $colors['green'] + $colors['blue']) / 3);
imagecolorset($img->getImageResource(), $i, $g, $g, $g);
}
【讨论】:
例如:
$file = 'image.jpg';
$file = 'image.gif';
$file = 'image.png';
$image_type = getimagesize($file);
switch (strtolower($image_type['mime'])) {
case 'image/png':
exec("convert $file -colorspace Gray dummy.png");
break;
case 'image/jpeg':
exec("convert $file -colorspace Gray dummy.jpeg");
break;
case 'image/gif':
exec("convert $file -colorspace Gray dummy.gif");
break;
default:
die;
}
【讨论】: