1

我在 350px x 350px 大的 div 中显示图片。人们可以将图片上传到我的文件服务器,并在数据库中创建指向该图片的目标链接以及一个 ID。获取链接的 php 文档位于根文件夹中,所有图片都保存在名为 Pictures 的子文件夹中。我使用这样的东西显示图片:

$piclink = "SELECT `link` FROM `pictures` WHERE `id=`.$id.`";

$id单击上一页中的链接时会存储该变量。

我的问题:并非所有图片的格式都相同。我想显示它们,使最大尺寸为 350px,另一个尺寸根据比例。我该怎么做呢?只需这样做:

echo "<img href=" . $piclink . " height='350px' width='350px'/>"

会将图片拉伸到 350x350,从而破坏比例。任何帮助表示赞赏。

4

1 回答 1

1

要保留纵横比,您可以检索图像尺寸并使用 350 像素的最大值应用该比率。

这是一个例子:

HTML

<div id="img-holder"></div>

代码

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"

这是 jsfiddle:http: //jsfiddle.net/aN6Ec/

于 2013-03-15T01:45:02.130 回答