PHP Snippets
image_constraints
Information
(PHP Version >= 4.0.6)Functions used in this snippet: imagesx, imagesy, imagecreatetruecolor, imagecopyresized.
Description
int image_constraints( int img, int dimx, int dimy )
Creates a resized image with the maximum width being dimx and height dimy without distorting the image.
Snippet
<?php
function image_constraints($img, $dimx, $dimy){
$x = imagesx($img);
$y = imagesy($img);
$xorg = $x;
$yorg = $y;
$altered = false;
if($x > $dimx){
$ratio = ($dimx / $x);
$x = $ratio * $x;
$y = $ratio * $y;
$altered = true;
}
if($y > $dimy){
$ratio = ($dimy / $y);
$y = $ratio * $y;
$x = $ratio * $x;
$altered = true;
}
if(!$altered){
return $img;
}
$dest = imagecreatetruecolor($x, $y);
imagecopyresized($dest, $img, 0, 0, 0, 0, $x, $y, $xorg, $yorg);
return $dest;
}
?>
Example
image_constraints Can be used in the following way:
<?php
$img = imagecreatefromjpeg('someimage.jpg'); // img size is 250 by 300 we will say
$img = image_constraints($img, 100, 100);
imagejpeg($img); // output image is 83 by 100
?>
Updated on May 14th at 3 pm.
4 Responses to image_constraints
This is exactly what I think I'll be needing in the near future and I found it by accident. Heya BigToach.
Good to know that somebody is using these things. :D
Okay, I fixed it. There was a floor in the ration which caused the ratio to be 0. Which means it tried to make an image 0x0 which is bad :( sorry about that.
Thanks Toachy.