BigToach.com

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$img0000$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($img100100);
imagejpeg($img); // output image is 83 by 100
?>

Added on Oct 9th at 7 pm by Scott - 4 Comments
Updated on May 14th at 3 pm.


4 Responses to image_constraints

Heri (zorroswordsman[at]gmail[dot]com) commented on Dec 6th at 11 am
This is exactly what I think I'll be needing in the near future and I found it by accident. Heya BigToach.
Scott commented on Dec 6th at 5 pm
Good to know that somebody is using these things. :D
Scott commented on May 14th at 3 pm
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.
Heri (zorroswordsman[at]gmail[dot]com) commented on May 14th at 5 pm
Thanks Toachy.

Name:

Site or Mail:

Comment:

To try to reduce the ammount of spam, please enter the word GOOSE in the following form

Security Code: