PHPverse 2025

Voting

: five plus three?
(Example: nine)

The Note You're Voting On

rayg at daylongraphics dot com
17 years ago
Here's a simple function to resample one JPEG imagefile to another while keeping aspect ratio of the source within the destination's dimensions. You can also tune the allowable distortion if you end up making too many thumbnails with thin blank areas around them. Should work when enlarging images too. Function returns true if it worked, false if not.

function resample_picfile($src, $dst, $w, $h)
{
// If distortion stretching is within the range below,
// then let image be distorted.
$lowend = 0.8;
$highend = 1.25;

$src_img = imagecreatefromjpeg($src);
if($src_img)
{
$dst_img = ImageCreateTrueColor($w, $h);
/* if you don't want aspect-preserved images
to have a black bkgnd, fill $dst_img with the color of your choice here.
*/

if($dst_img)
{
$src_w = imageSX($src_img);
$src_h = imageSY($src_img);

$scaleX = (float)$w / $src_w;
$scaleY = (float)$h / $src_h;
$scale = min($scaleX, $scaleY);

$dstW = $w;
$dstH = $h;
$dstX = $dstY = 0;

$scaleR = $scaleX / $scaleY;
if($scaleR < $lowend || $scaleR > $highend)
{
$dstW = (int)($scale * $src_w + 0.5);
$dstH = (int)($scale * $src_h + 0.5);

// Keep pic centered in frame.
$dstX = (int)(0.5 * ($w - $dstW));
$dstY = (int)(0.5 * ($h - $dstH));
}

imagecopyresampled(
$dst_img, $src_img, $dstX, $dstY, 0, 0,
$dstW, $dstH, $src_w, $src_h);
imagejpeg($dst_img, $dst);
imagedestroy($dst_img);
}
imagedestroy($src_img);
return file_exists($dst);
}
return false;
}

<< Back to user notes page

To Top