Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Imagick - Make black background white

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;
?>
like image 298
user2360906 Avatar asked Dec 06 '22 06:12

user2360906


2 Answers

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.

like image 184
kojow7 Avatar answered Dec 20 '22 21:12

kojow7


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);
like image 30
Simon Epskamp Avatar answered Dec 20 '22 23:12

Simon Epskamp