PHP 8.5.0 Alpha 4 available for testing

Voting

: min(three, seven)?
(Example: nine)

The Note You're Voting On

sam at durosoft.com
11 years ago
The ultimate smart image re-sizing routine. You provide the original image, and a desired width and/or height. The function will intelligently re-size the original image to fit, centered, within the specified dimensions. Either width or height can be omitted to have the re-size "lock" only on width or height. Fantastic for thumbnail generation. Designed to work with PNG's.

function resize_image_smart($orig, $dest_width=null, $dest_height=null)
{
$orig_width = imagesx($orig);
$orig_height = imagesy($orig);
$vertical_offset = 0;
$horizontal_offset = 0;
if($dest_width == null)
{
if($dest_height == null)
{
die('$dest_width and $dest_height cant both be null!');
}
// height is locked
$dest_width = $dest_height * $orig_width / $orig_height;
} else {
if($dest_height == null)
{
// width is locked
$dest_height = $dest_width * $orig_height / $orig_width;
} else {
// both dimensions are locked
$vertical_offset = $dest_height - ($orig_height * $dest_width) / $orig_width;
$horizontal_offset = $dest_width - ($dest_height * $orig_width) / $orig_height;
if($vertical_offset < 0) $vertical_offset = 0;
if($horizontal_offset < 0) $horizontal_offset = 0;
}
}
$img = imagecreatetruecolor($dest_width, $dest_height);
imagesavealpha($img, true);
imagealphablending($img, false);
$transparent = imagecolorallocatealpha($img, 0, 0, 0, 127);
imagefill($img, 0, 0, $transparent);
imagecopyresampled($img, $orig, round($horizontal_offset / 2),
round($vertical_offset / 2),
0,
0,
round($dest_width - $horizontal_offset),
round($dest_height - $vertical_offset),
$orig_width,
$orig_height);
return $img;
}

<< Back to user notes page

To Top