在PHP中将上传的图像转换为灰度 [英] convert uploaded image to grey scale in PHP

查看:527
本文介绍了在PHP中将上传的图像转换为灰度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a script that uploads a picture and resizes it, which all works fine, but I wanted to be able to strip the color out of the image leaving it black and white (various shades of grey essentially). I wasn't sure of how to achieve this?

谢谢

推荐答案

尝试以下几点:

<?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);
?>

请注意,我已经从这篇文章,我发现使用谷歌搜索的条款: php将图像转换为灰度

Notice that I have shamelessly ripped this snippet from this article, which I found using a google search with the terms: php convert image to grayscale

[edit]
从评论中,如果您使用PHP5,您还可以使用:

[ edit ] And from the comments, if you use PHP5, you could also use:

imagefilter($im, IMG_FILTER_GRAYSCALE); 

这篇关于在PHP中将上传的图像转换为灰度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆