I'm totally baffled - when reszing images to thumbnails using php (ie user uploads image and the script resizes it), how do I resize it so it doesnt get distorted (so it's still proportional)
Printable View
I'm totally baffled - when reszing images to thumbnails using php (ie user uploads image and the script resizes it), how do I resize it so it doesnt get distorted (so it's still proportional)
I would get the origional image size for length and width, then figure out which is longer, and use that to define your new scale. Then you multiply that by the origional opposite side, and divide by the origional same side.
I.e.
Image is 50px long and 60px wide.
A=50
B=60
B is longer, so we will use this as our base.
Thumbs must be no more than 30 px wide
So:
A=50
B=60
newA = ?
newB = 30
newB * A / B = newA
30 * 50 / 60 = newA
1250 / 60 = new A
25 = newA
newA = 25
newB = 30
A = 50
B = 60
Both aspect ratios are (when A / B) = .8333333333333
Meaning your image would have remained in proper size :)
I found this in the PHP Manual User Notes:
PHP Code:
<?php
// Max height and width
$max_width = 125;
$max_height = 125;
// Path to your jpeg
$upfile '/path/to/file.jpg';
Header("Content-type: image/jpeg");
$size = GetImageSize($upfile); // Read the size
$width = $size[0];
$height = $size[1];
// Proportionally resize the image to the
// max sizes specified above
$x_ratio = $max_width / $width;
$y_ratio = $max_height / $height;
if( ($width <= $max_width) && ($height <= $max_height) )
{
$tn_width = $width;
$tn_height = $height;
}
elseif (($x_ratio * $height) < $max_height)
{
$tn_height = ceil($x_ratio * $height);
$tn_width = $max_width;
}
else
{
$tn_width = ceil($y_ratio * $width);
$tn_height = $max_height;
}
// Increase memory limit to support larger files
ini_set('memory_limit', '32M');
// Create the new image!
$src = ImageCreateFromJpeg($upfile);
$dst = ImageCreateTrueColor($tn_width, $tn_height);
ImageCopyResized($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
ImageJpeg($dst);
// Destroy the images
ImageDestroy($src);
ImageDestroy($dst);
?>