Remove white pixels from a jpeg

Ye' old general discussion board. Basically, for everything that isn't covered elsewhere. Come here to shoot the breeze, shoot your mouth off, or whatever suits your fancy.
This forum is not for asking programming related questions.

Moderator: General Moderators

Post Reply
relief8
Forum Newbie
Posts: 13
Joined: Fri Jan 25, 2008 4:28 pm

Remove white pixels from a jpeg

Post 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.
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: Remove white pixels from a jpeg

Post by califdon »

.jpeg specification doesn't support transparency. .gif and .png do.
User avatar
greyhoundcode
Forum Regular
Posts: 613
Joined: Mon Feb 11, 2008 4:22 am

Re: Remove white pixels from a jpeg

Post 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.
User avatar
Darhazer
DevNet Resident
Posts: 1011
Joined: Thu May 14, 2009 3:00 pm
Location: HellCity, Bulgaria

Re: Remove white pixels from a jpeg

Post 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.
User avatar
greyhoundcode
Forum Regular
Posts: 613
Joined: Mon Feb 11, 2008 4:22 am

Re: Remove white pixels from a jpeg

Post 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 :?:
Post Reply