Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert PNG to JPG and set transparent background to white with ImageMagick and PHP

How can I use ImageMagick (with the php extension) to set the transparent background to white when converting an image from PNG to JPEG?

like image 842
John Avatar asked Mar 12 '11 01:03

John


People also ask

How do I make the background of a JPEG transparent?

Select the picture that you want to create transparent areas in. Click Picture Tools > Recolor > Set Transparent Color. In the picture, click the color you want to make transparent.

Does PNG support transparency?

The GIF and PNG formats also both support transparency. If you need any level of transparency in your image, you must use either a GIF or a PNG. GIF images (and also PNG) support 1-color transparency. This basically means that you can save your image with a transparent background.


Video Answer


2 Answers

At time of writing, you have not specified which extension you are using, but if you were using the commandline, the command would be:

convert image.png -background white -flatten -alpha off image.jpg 

More information can be found on the Masking Usage documentation.

Using IMagick for instance, I think you could do this as follows:

(totally untested, never used IMagick and don't have it installed to test)

$image = new IMagick('image.png');  $flattened = new IMagick(); $flattened->newImage($image->getImageWidth(), $image->getImageHeight(), new ImagickPixel("white"));  $flattened->compositeImage($image, imagick::COMPOSITE_OVER, 0, 0);  $flattened->setImageFormat("jpg"); $flattened->writeImage('image.jpg');  $image->clear(); $image->destroy(); $flattened->clear(); $flattened->destroy(); 
like image 137
Orbling Avatar answered Oct 16 '22 05:10

Orbling


If you are using the Imagick extension:

<?php // load the source transparent png $i = new IMagick('image.png');  // set the background to white // you can also use 'rgb(255,255,255)' in place of 'white' $i->setImageBackgroundColor(new ImagickPixel('white'));  // flattens multiple layers $i = $i->flattenImages();  // the output format $i->setImageFormat('jpg');  // save to disk $i->writeImage('image.jpg');  // and/or output directly // header('Content-Type: '.$i->getFormat()); // echo $i->getImageBlob();  // cleanup $i->clear(); $i->destroy(); 
like image 27
Mike Causer Avatar answered Oct 16 '22 07:10

Mike Causer