Jonnny
Jonnny

Reputation: 5039

convert uploaded image to grey scale in 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?

Thanks

Upvotes: 4

Views: 9043

Answers (3)

vijay
vijay

Reputation: 729

It's better to use command tool to convert such type of image.

While animated gif is also support.

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

Upvotes: 1

Jan Franc
Jan Franc

Reputation: 21

The easiest solution is to use imagefilter($im, IMG_FILTER_GRAYSCALE); But every single method mentioned here is not working for 100%. All of them is counting on color palette of the image, but the shades of gray might be missing and another color from the palette is used.

My solution is to replace colors in the color palette using 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);
}

Upvotes: 2

Yuri
Yuri

Reputation: 2028

Try something along these lines:

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

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 ] And from the comments, if you use PHP5, you could also use:

imagefilter($im, IMG_FILTER_GRAYSCALE); 

Upvotes: 12

Related Questions