user2360906
user2360906

Reputation: 117

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;
?>

Upvotes: 4

Views: 18479

Answers (3)

kojow7
kojow7

Reputation: 11394

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.

Upvotes: 13

Simon Epskamp
Simon Epskamp

Reputation: 9976

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);

Upvotes: 7

DonOfDen
DonOfDen

Reputation: 4088

Try this out: Background Color White:

<?php 
$image = new imagick( "opossum.jpg" ); 
$image->setimagebackgroundcolor("#fad888"); //Here you can mention the color
$image->waveImage( 20, 176); 
header( "Content-Type: image/jpeg" ); 
echo $image;
?>

Transparent background:

<?php 
$im = new Imagick(); 
$im->setBackgroundColor(new ImagickPixel('transparent')); 

$im->readImage('carte_Alain2.svg'); 

$im->setImageFormat("png32"); 

header('Content-type: image/png'); 
echo $im; 
?>

Also check this Links:

http://php.net/manual/en/imagick.setbackgroundcolor.php

Upvotes: 0

Related Questions