Log in

View Full Version : Constrain Proportions



john0611
08-17-2009, 06:24 PM
Hi all,

Any ideas on how to constrain images echoed from DB via directory:

Here is the source:


<a href="<?php echo $_SERVER['BASE_NAME']; ?>img/galleries/drawings/<?php echo $row['Filename']; ?>" rel="lightbox" title="<?php echo $row['Caption']; ?>"><img src="img/galleries/drawings/thumbs/<?php echo $row['Filename']; ?>" alt="<?php echo $row['Caption']; ?>" title="<?php echo $row['Caption']; ?>" width="120" height="120" /></a>

Problem is I need the box to remain in its dimensions, but have the image resize with out being distorted.

Any ideas? thanks for any help and suggestions.

JShor
08-18-2009, 01:40 PM
You can resize the image to a percentage w*h. For example, let's say your image is 300 x 500 pxls. You loop it per percentage until the height is 120pxls or below [-70%]. You would subtract that same -70% from the width so that the final dimensions are 70 x 120 [at or below the image specifications, w/o distorting it.]

This code should work for that:


<?php

$size = getimagesize($filename);
$width = $size[0];
$height = $size[1];

function loopResize($w, $h) {
$percent = 10%; // percentage to resize per loop, can be chged for a more approximate calculation
$percentW = ($width / 100) * $percent;// calc perct.
$percenH = ($height / 100) * $percent; // calculate percent

$w = ($w - $percentW); //subtract {x} percent
$h = ($h - $percentH); //subtract {x} percent
if($w > 120) {
loopResize($w); // keep resizing until fit
}

if($h > 120) {
loopResize($h); // keep resizing until fit
}

} //end function

if($w > 120) {
loopResize($w);
}

if($h > 120) {
loopResize($h);
}

if(($h <= 120) && ($w <= 120)) {

echo '<a href="'.$_SERVER['BASE_NAME'].'img/galleries/drawings/'.$row['Filename'].'" rel="lightbox" title="'.$row['Caption'].'"><img src="img/galleries/drawings/thumbs/'.$row['Filename'].'" alt="'.$row['Caption'].'" title="'.$row['Caption'].'" width="120" height="120" /></a>'; // img dimensions fit, return the output.

}

?>


HTH:)