Nikolay
Nikolay

Reputation: 11

How to merge two graphics files? (PHP, Imagick)

I have two graphics file.

The first image - a background image in JPG format

The second file - PNG file with the figure in the center filled with white, with a black border on a path. The main background of transparent PNG file.

Question: How to merge two files with transparency (see image example)? Background of the first file should be placed inside the figure in the second file.

Scheme:

example images

Images:

PNG file - profiles.in.ua/tmp/sample2.jpg

JPG file - profiles.in.ua/tmp/sample1.png

PHP code:

$mask = new Imagick(realpath('mask.png'));
$pattern = new Imagick(realpath('pattern.jpg'));
$pattern->resizeImage($mask->width, $mask->height, Imagick::FILTER_LANCZOS, 1);
$pattern->compositeImage($mask, Imagick::COMPOSITE_ATOP, 0, 0);
header("Content-Type: image/png");
echo $pattern->getImageBlob();
$mask->destroy();
$pattern->destroy();

Upvotes: 1

Views: 1090

Answers (2)

Moshe Kamer
Moshe Kamer

Reputation: 27

You need to fix the end of your code. All good until the end.

$base->writeImage('output.png');
header("Content-Type: image/png");
echo $base; 

Update me :)

Upvotes: 0

Matt Raines
Matt Raines

Reputation: 4218

Assuming the mask image is always made exclusively of white pixels (which should be overwritten with the pattern), black pixels (which should overwrite the pattern), and transparent pixels (which should remain transparent), you can get this effect by compositing the pattern into the non-transparent pixels in the mask, then darkening the result with the mask.

The PNG file you provided did not have a transparent background as specified; instead it was white and grey hatching. I had to edit it first to add a transparent background before this code worked.

$mask = new Imagick(realpath('sample1.png'));
$pattern = new Imagick(realpath('sample2.jpg'));
$pattern->resizeImage($mask->width, $mask->height, Imagick::FILTER_LANCZOS, 1);

$image = clone($mask);
$image->compositeImage($pattern, Imagick::COMPOSITE_IN, 0, 0);
$image->compositeImage($mask, Imagick::COMPOSITE_DARKEN, 0, 0);

header("Content-Type: image/png");
echo $image;

$image->destroy();
$mask->destroy();
$pattern->destroy();

Upvotes: 2

Related Questions