Reputation: 1989
I'm displaying pictures within a div that is 350px x 350px big. People can upload pictures to my fileserver and a destination link to that picture is created in a database as well as an id. The php document getting the link is in the root folder and all pictures are saved in a subfolder called pictures. I show the picture using something like this:
$piclink = "SELECT `link` FROM `pictures` WHERE `id=`.$id.`";
The $id
variable is stored when clicking a link from the previous page.
My problem: Not all pictures are the same format. I want to display them so that the max dimension is 350px, the other dimension according to proportion. How do I do this? Simply doing this:
echo "<img href=" . $piclink . " height='350px' width='350px'/>"
will stretch the picture to 350x350 thus breaking proportions. Any help appreciated.
Upvotes: 1
Views: 125
Reputation: 10780
To retain the aspect ratio, you can retrieve the image dimensions and apply the ratio using the 350px maximums.
Here's an example:
HTML
<div id="img-holder"></div>
Code
var img = new Image();
img.onload = function () {
alert('Orignal width:'+img.width+', height:'+img.height);
var width, height;
if (img.width > img.height) {
width = (img.width > 350 ? 350 : img.width);
height = img.height * (350 / img.width);
} else {
height = (img.height > 350 ? 350 : img.height);
width = img.width * (350 / img.height);
}
img.width=width;
img.height=height;
$("#img-holder").append(img);
}
img.src = "http://mps.thebeautyquotient.com/images/val4a.jpeg"
Here's the jsfiddle: http://jsfiddle.net/aN6Ec/
Upvotes: 1