Page 1 of 1

Remove white pixels from a jpeg

Posted: Wed Jul 14, 2010 10:27 am
by relief8
Hello,

Has anyone ever displayed a jpeg image on their site and used php to remove the white pixels (or make them transparent)? I have been searching for a way to do this but have been unsuccessful. Any links to a tutorial or some sample code would be great.

Thanks for the help.

Re: Remove white pixels from a jpeg

Posted: Thu Jul 15, 2010 12:13 am
by califdon
.jpeg specification doesn't support transparency. .gif and .png do.

Re: Remove white pixels from a jpeg

Posted: Sat Jul 17, 2010 12:55 pm
by greyhoundcode
I don't see why you couldn't load from JPG and output to PNG, if GD is available of course.

Code: Select all

// Definitions
$imageFile          = 'your_chosen_image.jpg';
$imgResource        = 0;
$myTransparentColor = 0;

// Load the image
$imgResource = imagecreatefromjpeg($imageFile);

// Define the color to become transparent
$myTransparentColor = imagecolorallocate($imgResource, 0, 0, 0);

// Make it transparent
imagecolortransparent($imgResource, $myTransparentColor);

// Output to PNG
imagepng($imgResource);
Haven't tested it so it might need some tinkering with.

Re: Remove white pixels from a jpeg

Posted: Sat Jul 17, 2010 1:18 pm
by Darhazer
The problem is that there are a lot of different colors, that are 'white', but are with different hex code. Since JPEG is a lossy format, even if the original image was with natural (#fff) white color, the JPEG will have a lot of different shades of white. Hence, you can not make it transparent, unless you don't know all the possible pixels you would like to hide.

Re: Remove white pixels from a jpeg

Posted: Sat Jul 17, 2010 2:07 pm
by greyhoundcode
Very true.

Circumstances depending, however, we could take our image resource and convert it to a paletted image - wouldn't that negate some of the problems of various 'shades' of white?

Just an idea :?: