php imagick convert PNG to jpg
Found a solution:
$white=new Imagick();
$white->newImage($width, $height, "white");
$white->compositeimage($image, Imagick::COMPOSITE_OVER, 0, 0);
$white->setImageFormat('jpg');
$white->writeImage('image.jpg');
Another way to convert transparent png to jpg, as mentioned in Imagick::flattenImages:
$im = new Imagick('image.png');
$im->setImageBackgroundColor('white');
$im->flattenImages(); // This does not do anything.
$im = $im->flattenImages(); // Use this instead.
$im->setImageFormat('jpg');
$im->writeImage('image.jpg');
As time moves on, flattenImages()
has been deprecated.
Instead of the line above use:
$im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
You can use setBackgroundColor
to set the default background color to something else than black. The PNG transparency will be replaced by the background color when saving to JPG.
Edit: Use it like so:
$img->setBackgroundColor(new ImagickPixel('#FFFFFF'));