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 distort开发者_开发技巧ed. How can I fix this?
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/
you can get the image size using php:
list($width, $height) = getimagesize($file);
Try something like this:
$ratio = $height / $width;
$new_width = 150;
$new_height = $ratio * $new_width;
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" />
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.
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
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.
精彩评论