Page 1 of 1

Resize and crop to fit bounds

Posted: 2009-12-10T02:35:16-07:00
by bjornie
Hey!

I'm having some troubles with resizing and cropping images.

Say I want to convert any image larger than 300x150 to be resized and cropped to 300x150 - even if the original image is out of scale. I have images in 415x1090, 1245x400, 500x500, and so on - and I want all of these images to fit exactly in a 300x150 box with perspective from the center of the image. How can I achieve this? All my tries have ended up with images in the wrong scale or in the wrong perspective.

Best regards,
Björn

Re: Resize and crop to fit bounds

Posted: 2009-12-10T03:47:06-07:00
by bjornie
Got it working with two calls to imagemagick, but a oneliner would be preferred.

PHP calling imagemagick:

Code: Select all

   $from     = '/tmp/myimage.jpg';
   $to       = '/tmp/formatted.jpg';
   $toWidth  = 300;
   $toHeight = 150;
   $quality  = 80;

   list($imageWidth, $imageHeight, $type, $attr) = getimagesize($from);

	if (($toWidth / $imageWidth) >= ($toHeight/$imageHeight)) {
		$tmp = substr($to, 0, strrpos($to, '/')) . '/' . rand(0, 1000) . '-' . substr($to, strrpos($to, '/') + 1);
		exec('/usr/bin/convert "' . $from . '" -resize ' . $toWidth . 'x -quality ' . $quality . ' "' . $tmp . '"');
		exec('/usr/bin/convert "' . $tmp  . '" -gravity Center -crop ' . $toWidth . 'x' . $toHeight . '+0+0 "' . $to . '"');
		unlink($tmp);
	} else {
		$tmp = substr($to, 0, strrpos($to, '/')) . '/' . rand(0, 1000) . '-' . substr($to, strrpos($to, '/') + 1);
		exec('/usr/bin/convert "' . $from . '" -resize x' . $toHeight . ' -quality ' . $quality . ' "' . $tmp . '"');
		exec('/usr/bin/convert "' . $tmp  . '" -gravity Center -crop ' . $toWidth . 'x' . $toHeight . '+0+0 "' . $to . '"');
		unlink($tmp);
	}

Re: Resize and crop to fit bounds

Posted: 2009-12-10T09:59:19-07:00
by fmw42
If you don't care about change in aspect ratio, then (note the !) see http://www.imagemagick.org/script/comma ... p#geometry

convert image -resize '350x150!' result

If you want to maintain aspect ratio and don't mind some padding (black or any other color, even transparent/none ), then (no !)

convert image -resize 350x150 -gravity center -background black -extent 350x150 result

Re: Resize and crop to fit bounds

Posted: 2009-12-10T10:41:42-07:00
by Bonzo
Try:

Code: Select all

<?php

$input = "yorkshire.jpg";
$toWidth  = "300";
$toHeight = "150";
$quality  = "80";

 exec("convert $input -resize \"{$toWidth}x{$toHeight}^\" -gravity center -crop {$toWidth}x{$toHeight}+0+0 +repage output_crop.jpg");
 
 ?>

Re: Resize and crop to fit bounds

Posted: 2009-12-10T10:48:47-07:00
by fmw42
You can do it either by cropping (as Bonzo suggests) or padding as I suggested. Depends upon how you want to handle it. I have a script, called aspect, that allows you to choose which way you want to do this. See link below.