Layering images of unqual size

IMagick is a native PHP extension to create and modify images using the ImageMagick API. ImageMagick Studio LLC did not write nor does it maintain the IMagick extension, however, IMagick users are welcome to discuss the extension here.
Post Reply
pwnedd
Posts: 35
Joined: 2008-09-03T13:03:57-07:00

Layering images of unqual size

Post by pwnedd »

Hi all,

I've slowly been getting the hang of Imagick. I can now stitch together and composite multiple images, but I'm having trouble doing it when the images
to be composited have differing dimensions.

The goal is to take two images with different sizes, layer them with the smaller one behind the larger one, center them, and then flatten it and print
it to the screen.

My approach on the command-line (perhaps not the best, but a start), is:

1. mogrify the smaller image to extend the canvas so that it matches the larger image:

Code: Select all

mogrify -bordercolor transparent -border 256x256 smaller_image.jpg
2. composite the images using "center" gravity:

Code: Select all

composite front.png smaller_image.jpg -gravity center composite.png
I haven't found a way, however, to imitate this in PHP. I can composite the images,
but if I do it the way I would for equally-sized images, only the corner of the larger image is shown.
If I switch the order, I can get the canvas to take on the size of the larger image, however, then the
placement and centering is off.

Does anyone have any ideas? Any help would be greatly appreciated.

Thanks!
Keith
pwnedd
Posts: 35
Joined: 2008-09-03T13:03:57-07:00

Re: Layering images of unqual size

Post by pwnedd »

In case anyone is interested, I figured out a way to achieve this.

The below code takes two images: one 1024x1024 image and one 2048x2048 image. The larger image is then places on top of the smaller
one. Finally a black background is added to the new composite image.

Code: Select all

<?php
	// load images
	$small = new Imagick('small.jpg');
	$large = new Imagick('large.png');

	// composite images
	$large->compositeImage($small, imagick::COMPOSITE_PLUS, 512, 512);

	// create a black background (can do once for all images)
	$bg = new Imagick();
	$bg->newImage( 2048, 2048, new ImagickPixel("black") );

	// composite image on top of background
	$large->compositeImage($bg, imagick::COMPOSITE_PLUS, 0, 0);

	//display
	$large->setImageFormat( 'png' );
	header( "Content-Type: image/png" );
	echo $large;
?>
Cheers,
mkoppanen
Posts: 309
Joined: 2007-06-09T07:06:32-07:00

Re: Layering images of unqual size

Post by mkoppanen »

Hi,

good work and thanks for sharing the solution!
Mikko Koppanen
My blog: http://valokuva.org
Post Reply