7

I have a lot of JPEG images that I want to convert to PNG images using PHP. The JPEGs are going to be uploaded by clients so I can't trust them to make sure they are in the right format.

I also want to make their white backgrounds transparent.

Does PHP have any functions I can use to achieve this?

Max Rose-Collins
  • 1,904
  • 5
  • 26
  • 45

4 Answers4

10

After a few days of trying different solutions and doing some more research, this is what I found worked for me.

 $image = imagecreatefromjpeg( 'image.jpg' );
 imagealphablending($image, true);
 $transparentcolour = imagecolorallocate($image, 255,255,255);
 imagecolortransparent($image, $transparentcolour)

The imagealphablending($image, true); is important.

Using imagesavealpha($f, true); as mentioned in a previous answer definitely doesn't work and seems to actually prevent you from making the background transparent...

To output the transparent image with the correct headers.

<?php
     header( 'Content-Type: image/png' );
     imagepng( $image, null, 1 );
?>
Max Rose-Collins
  • 1,904
  • 5
  • 26
  • 45
7
$f = imagecreatefromjpeg('path.jpg');
$white = imagecolorallocate($f, 255,255,255);
imagecolortransparent($f, $white);

More details here

genesis
  • 50,477
  • 20
  • 96
  • 125
  • 6
    Assuming this will work, mind that JPG is a lossy format. That means that colors may be off a little, especially around the edges and in places where the color changes from white to another color. Looking for just plain white will probably not find all the pixels you want to be transparent. – GolezTrol Sep 30 '11 at 12:15
  • 1
    Just to complete this answer: use `imagesavealpha($f, true);` to ensure the alpha channel is saved and `imagepng($f, '/path/to/save/file.png');` to save as PNG. – daiscog Sep 30 '11 at 12:17
  • @awm added to my answer if you do not care – genesis Sep 30 '11 at 12:23
0

This worked for me:

 $image = imagecreatefromjpeg( "image.jpg" );
 imagealphablending($image, true);
 imagepng($image, "image.png");
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
-3

I found this solution at Convert jpg image to gif, png & bmp format using PHP

$imageObject = imagecreatefromjpeg($imageFile);
imagegif($imageObject, $imageFile . '.gif');
imagepng($imageObject, $imageFile . '.png');
imagewbmp($imageObject, $imageFile . '.bmp');
Community
  • 1
  • 1
Nimit Dudani
  • 4,840
  • 3
  • 31
  • 46