Page 1 of 1

Reduce image size but keep aspect ratio

Posted: Thu Dec 04, 2003 4:51 pm
by Cruzado_Mainfrm
ok, is not resizing actually, the thing is that i have two numbers, and i have to lower them equally, so the ratio is still the same.

for example i have an image that it's 570w x 324h, i have to reduce it until none of the width and height are more than 50pixels. I have been trying to do this but my head can take that pressure right now, can someone tell me if i can find a library for this or something helpful?

Posted: Thu Dec 04, 2003 5:00 pm
by uberpolak
Why don't you just do this?

Code: Select all

<?php $h = round(324 * (50/570)); ?>

<img src="file.gif" width="50" height="<?php echo $h; ?>">

Posted: Thu Dec 04, 2003 5:07 pm
by microthick
You can use JavaScript to find the image width and height of each image, then compare them to see which is larger and reduce by ratio.

document.getElementById('test').width will return the width of the image with id 'test'.

Posted: Thu Dec 04, 2003 5:38 pm
by Cruzado_Mainfrm
well, i think u guys didn't get me, let me explain a bit more...

if you have an image for example, that is 500 x 300 pixels, and u want to reduce it until neither the width and height are more than 50 the image size will now be 50x30 pixels, it keeps the same ratio 500:300 = 50:30
see what i mean? :D

note: width and height are variables, they CAN change...

Posted: Thu Dec 04, 2003 10:08 pm
by Nay
Maybe put it in a while loop?

I'm not 100% but how about something like:

Code: Select all

$width = 500;
$height = 300;

While($width > 50):

$width = $width / 10;
$height = $height / 10;

EndWhile;

If($width =< 50):
echo <<< IMG
<img src="theimage.jpg" alt="theimage" style="width:$width; height$height;" />
IMG;
EndIf;
-Nay

Posted: Thu Dec 04, 2003 10:34 pm
by Chambrln
You would need to either store the original size of the image in a db or look at the image when you go to display it to find out its size. Once you know the size determine which is the larger of the two

Divide the larger size by 50.

Take the result of that answer and divide the smaller size by the answer.

Code: Select all

<?php
$width = 320;
$height = 420;

if ($width > $height) {
  $divisor = ($width/50);
  $new_width = 50;
  $new_height = ($height/$divisor);
} elseif ($width < $height) {
  $divisor = ($height/50);
  $new_height = 50;
  $new_width = ($width/$divisor);
}

echo "<img src="image.jpg" width="$new_width" height="$new_height" border=0>";


?>

Posted: Fri Dec 05, 2003 5:10 pm
by Cruzado_Mainfrm
actually none of them work as expected, but Nay's proposition was better, i just changed the division by 10 to substract - 1 and added another condition to the while:

Code: Select all

<?php
<?php 
$width = 100; 
$height = 100; 
While($width > 50 || $height > 50){
$width = $width - 1; 
$height = $height - 1; 
}
If($width <= 50) {
echo "<img src="imagetest.gif" alt="theimage" style="width:$width; height$height;" />"; 
}
?>
?>