1

i don't know if this question fits here but i want to understand the formula for resizing an image while keeping the ratio in PHP GD library or in anything else.

For example here is an example: http://salman-w.blogspot.com/2008/10/resize-images-using-phpgd-library.html

In this example if "target_aspect_ratio" is bigger than "original_aspect_ratio" height is targe_height and width is calculated by target_height * original_aspect_ratio.

If "original_aspect_ratio" is bigger than "target_aspect_ratio" target width is target_width and height is calculated by target_width / original_aspect_ratio

Why is that?

user1002601
  • 379
  • 5
  • 19

1 Answers1

1

The way that I always resize images when maintaining the ratio is to use an algorith like the following:

$imgHeight=600; // Or the actual image height.
$imgWidth=300;  // Or again the width of the image
$imgRatio=$imgHeight/$imgWidth;

Then to resize the image you can use the following:

$newHeight=1000;
resize($newHeight, ($newHeight/$imgRatio)); 
// assumes Height x Width in the resize command.

With this method, you get the ratio of the original image, then apply it to whatever size you need.

Edit:

If you are doing thumbnails, you often will want to keep the image size of all the thumbnails the same exact size - so they line up nicely on a page. I would suggest resizing the image so that the resized image fits INSIDE the actual thumbnail - basically giving it space on either the top or bottom, and then fill that in with a background color or leave it transparent so that it works with the rest of the site.

Fluffeh
  • 33,228
  • 16
  • 67
  • 80
  • Is that all? With this can i create let's say a thumbnail of 200x150, a tiny image, a medium size image and a large image from a source image keeping the ratio. – user1002601 Sep 16 '13 at 12:24
  • I gave you pseudo-code, am sure you will need to adjust to the actual syntax (it's been years since I did image resizes) but the logic still stands, and yes, will resize thumbnails perfectly. Also, will add a little edit on that note. – Fluffeh Sep 16 '13 at 12:25
  • Of course real code is not necessary only the logic behind it. – user1002601 Sep 16 '13 at 12:27
  • Okay, have a gander at the edit that I added - more musing and interface to keep a site tidy. – Fluffeh Sep 16 '13 at 12:29
  • What do you think about the example in the link i posted. He uses if/else statements for different situations. Is your code encompasses these situations? Those if/else statements are redundant? – user1002601 Sep 16 '13 at 12:32