Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use PHP to convert JPEGs to transparent PNG

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?

like image 489
Max Rose-Collins Avatar asked Sep 30 '11 12:09

Max Rose-Collins


People also ask

How do I make a JPEG image transparent?

Add a transparent area to a pictureClick Picture Tools > Recolor > Set Transparent Color. In the picture, click the color you want to make transparent.

Can a JPG be made transparent?

Convert your JPG files into transparent PNGS in just one step. The remove background tool allows you to highlight the subject of your photo and create a transparent background, so that way you can place your new image into a variety of new designs and destinations.

How do I make a PNG file transparent?

Save As A Transparent PNG ImageClick “File” -> “Save As”. Select “PNG (*. PNG) as the file format. Note that though a transparent background looks checkered in Photoshop, it will actually be transparent in the final PNG file.


1 Answers

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 );
?>
like image 194
Max Rose-Collins Avatar answered Oct 06 '22 00:10

Max Rose-Collins