thumbnail ratio calculation

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
amir
Forum Contributor
Posts: 287
Joined: Sat Oct 07, 2006 4:28 pm

thumbnail ratio calculation

Post by amir »

i need a function/code sample to calculate a size ratio of any image
example:
original.jpg - 615x355
thumb will allways be - 150x110

so i need to resize it to be the closest to 150x110, but a bit more...
and then i'll crop it out to be 150x110

TIA!
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

create a scale, divide both the height and width by that scale, find the min of those two using the min() function, use that result to figure the sizes.
User avatar
bokehman
Forum Regular
Posts: 509
Joined: Wed May 11, 2005 2:33 am
Location: Alicante (Spain)

Post by bokehman »

Try the function below. In case of cropping the height (rather than just resizing) the crop bias is to the upper part of the image (which is normally of greater importance). In case cropping is needed to the width this is done equally.

Code: Select all

function ResizeSemiAbstractTop($SourceJpeg, $destination = NULL, $w = 120, $h = 90, $quality = 100)
{
	$source_image = @imagecreatefromjpeg($SourceJpeg)
		or die($SourceJpeg.' is not a valid image');
	$sw = imagesx($source_image);
	$sh = imagesy($source_image);
	$ar = $sw/$sh;
	$tar = $w/$h;
	if($ar >= $tar)
	{
		$x1 = round(($sw - ($sw * ($tar/$ar)))/2);
		$x2 = round($sw * ($tar/$ar));
		$y1 = 0;
		$y2 = $sh;
	}
	else
	{
		$x1 = 0;
		$y1 = 0;
		$x2 = $sw;
		$y2 = round($sw/$tar);
	}
	$slate = @imagecreatetruecolor($w, $h) or die('Invalid thumbnail dimmensions');
	imagecopyresampled($slate, $source_image, 0, 0, $x1, $y1, $w, $h, $x2, $y2);
	$destination or header('Content-type: image/jpeg');
	@imagejpeg($slate, $destination, $quality) or die('Directory permission problem');
	ImageDestroy($slate);
	ImageDestroy($source_image);
	$destination or die;
	return true;
}
Post Reply