Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transparent to white in Imagick for PHP

Tags:

I have a png image with a transparent background and I want to convert it to a jpg image with a white background.

The code is basically this:

$image = new Imagick('transparent.png');
$image->writeImage('opaque.jpg');

But that creates a black background jpg. I've been struggling with the worst documentation ever trying to find a way to convert the transparent to white to no avail.

Edit: Well, I tried Marc B's idea and kind of got it to work.

$image = new Imagick('transparent.png');
$white = new Imagick();

$white->newImage($image->getImageWidth(), $image->getImageHeight(), "white");
$white->compositeimage($image, Imagick::COMPOSITE_OVER, 0, 0);
$white->writeImage('opaque.jpg');

$image->destroy();
$white->destroy();

The problem now is, it always causes the script to segfault.

like image 400
fonso Avatar asked Feb 11 '11 19:02

fonso


2 Answers

Try:

$image = new Imagick('transparent.png');
$image->setImageMatte(true);
$image->setImageMatteColor('white');
$image->setImageAlphaChannel(Imagick::ALPHACHANNEL_OPAQUE);
$image->writeImage('opaque.jpg');
like image 24
chaos Avatar answered Sep 20 '22 15:09

chaos


flattenImages() actually works.

But keep in mind that it doesn't modify the given \Imagick() object but returns a new one:

$image = new \Imagick('transparent.png');

// Need to use the result of $image->flattenImages() here!
$image = $image->flattenImages();
$image->writeImage('opaque.jpg');

flattenImages() defaults to the background color white. If you want to use another background color you have to set it before loading the image:

$image = new \Imagick();

// Needs to be called before the image is loaded!
$image->setbackgroundcolor('green');
$image->readimage('transparent.png');

$image = $image->flattenImages();
$image->writeImage('opaque.jpg');

In general the Imagick API is very sensible when it comes to the order of function calls (just like convert and its parameters on the command line) so always check if your order is correct.

Good luck!

Edit April 2016:

$image->flattenImages() was deprecated and should be replaced by:

$image->mergeImageLayers(\Imagick::LAYERMETHOD_FLATTEN)

It's hard to find exact informations about this, but it seems that this applies to PHP >= 5.6.

Thanks to vee for the tip!

like image 55
flu Avatar answered Sep 17 '22 15:09

flu