I am using the following code to mask one image on another image. On output, it gives me an image with Black background.
But I need a white background or a transparent background.
Following is the code that I am using to mask one image over another.
<?PHP
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$im1="image1.png";
$im2="image2.png";
$i1="$destination_path$im1";
$i2="$destination_path$im2";
$base = new Imagick($i1);
$mask = new Imagick($i2);
// Setting same size for all images
$base->resizeImage(274, 275, Imagick::FILTER_LANCZOS, 1);
// Copy opacity mask
$base->compositeImage($mask, Imagick::COMPOSITE_DSTIN, 0, 0, Imagick::CHANNEL_ALPHA);
$base->writeImage('output.png');
header("Content-Type: image/png");
echo $base;
?>
The new method:
flattenImages() now seems to be deprecated.
If your PHP imagick module is 3.2.0b2 or greater, then the current solution is as follows:
$im->setImageBackgroundColor('#ffffff');
$im->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
$im = $im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
If your PHP imagick module is less than that, then the ALPHACHANNEL_REMOVE
constant is not recognized and you can use the following code instead:
$im->setImageBackgroundColor('#ffffff');
$im->setImageAlphaChannel(11);
$im = $im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
Checking your imagick version
To check your imagick module version, run the following command:
php --ri imagick
Note: the above command will give both the imagick version and the ImageMagick version. You are looking for the imagick version.
The trick is using: $im = $im->flattenImages();
:
<?php
$im = new Imagick($filename);
$im->setImageBackgroundColor('#ffffff');
$im = $im->flattenImages();
$im->setImageFormat("jpeg");
$im->setImageCompressionQuality(95);
$im->writeImage($filename);
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