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
You can try it by changing Imagick constant as shown below
//$image will conatains image which needs background to be transparent
$white = new Imagick();
$white->newImage($image->getImageWidth(), $image->getImageHeight(), new ImagickPixel( "white" ));
$white->compositeimage($image, Imagick::COMPOSITE_DEFAULT, $x1OfTransparentImage, $y1OfTransparentImage,);
$white->flattenImages();
$white->writeImage('opaque.jpg');
$white->destroy();
Try the following, it works for me:
$im = new Imagick('trans.png');
$im->setimagebackgroundcolor('white');
$im = $im->flattenimages();
$im->writeimage('transToWhite.jpg');
Hope that helps!
I ran into the same problem when converting PDFs to PNGs, and I used flattenImages().
//get the first page of the PDF
$im = new imagick( $file.'[0]' );
//set the background to white
$im->setImageBackgroundColor('white');
//flatten the image
$im = $im->flattenImages();
//do the rest of the image operations
$im->setResolution( 181, 181 );
$im->setCompressionQuality(100);
$im->resizeImage ( 181, 181, imagick::FILTER_LANCZOS, 1, TRUE);
$im->setImageFormat('png');
$imageName = $title.'_thumb.png';
Try:
$image = new Imagick('transparent.png');
$image->setImageMatte(true);
$image->setImageMatteColor('white');
$image->setImageAlphaChannel(Imagick::ALPHACHANNEL_OPAQUE);
$image->writeImage('opaque.jpg');