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.
Try:
$image = new Imagick('transparent.png');
$image->setImageMatte(true);
$image->setImageMatteColor('white');
$image->setImageAlphaChannel(Imagick::ALPHACHANNEL_OPAQUE);
$image->writeImage('opaque.jpg');
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With