在PHP中将上传的图像转换为灰度

时间:2011-11-23 15:43:59

标签: image-processing

我有一个上传图片并调整大小的脚本,这一切都运行正常,但我希望能够从图像中剥离颜色,留下黑白(各种灰色阴影)。我不确定如何实现这个目标?

由于

3 个答案:

答案 0 :(得分:8)

尝试以下几点:

<?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无耻地撕掉了这个片段,我发现这是使用谷歌搜索的条款: php将图像转换为灰度

[编辑] 从评论中,如果你使用PHP5,你也可以使用:

imagefilter($im, IMG_FILTER_GRAYSCALE); 

答案 1 :(得分:2)

最简单的解决方案是使用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);
}

答案 2 :(得分:1)

使用命令工具转换此类图像会更好。

动画gif也支持。

E.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;
}