Reputation: 5442
I'm listing photos using MySQL:
<?php
$a = mysql_query("select * from x");
?>
<?php while ($w=mysql_fetch_array($a)) { ?>
<img src="<?=$w[url]?>" alt="<?=$w[name]?>" width="150" height="110" />
<? } ?>
How can I can maintain the aspect ratio? An image with dimensions of 150x500 pixels becomes very distorted. How can I fix this?
Upvotes: 1
Views: 2066
Reputation: 23098
You could use a resize script to resample (resize) the image.
A good script is located here: http://shiftingpixel.com/2008/03/03/smart-image-resizer/
To use:
<img src="/image.php?image=/img/test.jpg&width=150&height=500" alt="Test" />
I you plan to always use this height/width you could insert the resampled image directly in the database. This way you won't waste space on your server. If you plan to use many height/width or change these sizes in the future, you should keep the originals as you do now.
Upvotes: 1
Reputation: 11595
Setting both the width and height of an forces the browser to rezise it to match what you tell it to.
Setting only one (either width or height) resizes it so that the image's ration is kept.
You can use the PHP function getImageSize
to get the image's actual width and height, and then rerform a proportional resize based on height / width = new_width / new_height
Upvotes: 1
Reputation: 3303
Try something like this:
$ratio = $height / $width;
$new_width = 150;
$new_height = $ratio * $new_width;
Upvotes: 3
Reputation: 1743
you can get the image size using php:
list($width, $height) = getimagesize($file);
Upvotes: 3
Reputation: 655229
Just specify one dimension (either the width or the height but not both) and it will keep the ratio. With CSS you could also specify just the maximum width and maximum height:
<img src="<?=$w[url]?>" alt="<?=$w[name]?>" style="max-width:150px; max-height:110px" />
Upvotes: 2
Reputation: 91734
If you just specify a width, all browsers (that I know of...) will scale the image correctly.
However, you might want to consider making thumbnails if you´re going to load a lot of images.
Upvotes: 1
Reputation: 8765
Just specifying width-only or height-only in the HTML will keep the ratio.
Or you can actually resize your photos dynamically with a script like the Smart Image resizer: http://shiftingpixel.com/2008/03/03/smart-image-resizer/
Upvotes: 3