0
votes

I am trying to either find a way to calculate the width and height ratio of an image so if I resize the image, it will proportionally resize correctly. Is there such a script?

For example an image is 500x750 and the container that holds the image is maximum 350 width...So I need the script to calculate what the height should be in proportion to the 350 width.

Thanks.

4

4 Answers

2
votes

Use Javascript.

See this tutorial: http://www.ajaxblender.com/howto-resize-image-proportionally-using-javascript.html

Using the function the other guy posted:

<?PHP

$imagePath = "images/your_image.png";

list($oldWidth, $height, $type, $attr) = getimagesize($image_path); 

$percentChange = $newWidth / $oldWidth;
$newHeight = round( ( $percentChange *$height ) );

echo '<img src="'.$imagePath.'" height="'.$new_height.'" width="'.$newWidth.'">';

?> 
1
votes

use getImagesize and get the new height by dividing by the aspect ratio.

list($width, $height, $type, $attr) = getimagesize("image.jpg");
$aspect = $width / $height;
$newWidth = 350;
$newHeight = $newWidth / $aspect;
1
votes

I think this is the php function you're looking for: getimagesize

From the manual:

Returns an array with 7 elements.

Index 0 and 1 contains respectively the width and the height of the image.

Here's a short example how to work with this for your problem:

// get the current size of your image
$data = getimagesize('link/your/image.jpg');

// your defined width
$new_width = 350;

// calculate the ratio
$ratio = $data[0] / $new_width;

// apply the ratio to get the new height of your image
$new_height = round($data[1] / $ratio);

...done!

1
votes

You tagged your question with the PHP tag, so assuming you want to use PHP:

To get an image's height or width from an image resource, use imagesx() and imagesy(). http://www.php.net/manual/en/function.imagesx.php
http://www.php.net/manual/en/function.imagesy.php

To get an image's height and width from an image file, use getimagesize(). Items 0 and 1 in the array returned by that function are the width and height of the image. http://www.php.net/manual/en/function.getimagesize.php

If you have an image that is 500 pixels wide and 750 pixels high, and you have a container that is 350 pixels wide, you can calculate the ratio by dividing the desired width by the actual width: 350/500 which is 0.7. So to calculate the height, multiply it by that ratio (750 * 0.7 or 525).