Mark Rogers wrote:
Eg: I have a 300x300 box to put a 400x600 image into. It would need reducing to 200x300 (so it fits the 300x300), then centred over (say) a black 300x300 rectangle to create the final image. Ideally the background colour, and alignment over the background, would be optional, but black and centred would normally be fine. Whenever I've used convert I've been unable to achieve this (I get the 200x300 bit easily, but that's where I get stuck). Given the myriad of options I've never been convinced the option I want isn't lurking there somewhere.
I've been lurking for a while (so by way of introduction - "hi all"). I thought I'd pipe up as this is a subject dear to my heart - I am a bit of a photo-obsessive and have over 11,000 photos on my website - most of which have been processed via Perl scripts using ImageMagick.
Here's a Perl example of implementing a composite of two images - your background (created on-the-fly) and your thumbnail:
########################################################## #!/usr/bin/perl #
use Image::Magick;
# create background...
$image = Image::Magick->new; $image->Set( size=>'300x200' ); $image->ReadImage( 'xc:black' );
# read image to add on top...
$image2 = Image::Magick->new; open ( IMAGE, 'myImageToAdd.jpg' ); $image2->Read( file=>*IMAGE );
$width = $image2->Get('width'); $height = $image2->Get('height');
if ( $width > $height ) {
# landscape print "landscape... "; $newwidth = 300; $ratio = $height / $width; $newheight = int( $mainsize * $ratio ); } else {
# portrait print "portrait... "; $newheight = 200; $ratio = $width / $height; $newwidth = int( $mainsize * $ratio ); }
$image2->Resize( width=>$newwidth, height=>$newheight, filter=>'Hamming' );
$image->Composite( image=>$image2, compose=>'Atop' ); $image->Set( quality=>"89" ); # set output JPEG quality $image->UnsharpMask( radius=>0.6, sigma=>0.7, amount=>0.7, threshold=>0.02 ); # took me /ages/ to get this right $image->Strip(); # remove space-hogging EXIF data, etc
$image->Write( 'test.jpg' ); #######################################################
Or something like that. You can fiddle around with the position your second image ends up with attributes such as Geometry - look at http://www.imagemagick.org/script/perl-magick.php and the section on "Composite".
Of course, as another poster pointed out, you could save a bit of bandwidth by wrapping your image in a suitable background-coloured table cell, <div> or <span>. Personally, I'm a big fan of cropped (as opposed to windowed) thumbnails - even though you do occasionally chop people's heads off!
Simon