从图像src生成缩略图

时间:2012-05-21 15:36:09

标签: javascript orientation aspect-ratio

我需要在幻灯片中生成一些拇指。对于每张幻灯片,这个拇指是从img src直接/动态生成的。

现在我正在为拇指库生成这样的代码:

<ul id="galThumb">
<li id="thumb0"><img src="path-to-image" title="Image[0]"></li>
<li id="thumb1"><img src="path-to-image" title="Image[1]"></li>
<li id="thumb2"><img src="path-to-image" title="Image[2]"></li>
...
<li id="thumbn"><img src="path-to-image" title="Image[n]"></li>
</ul>

li元素左浮动以获得它们的水平线。

我的问题是,用户可以上传任何图像大小和方向图像,我无法正确控制拇指的方面。我需要所有拇指都有特定的尺寸。例如,60x45px。

当用户上传垂直图像或具有不同比例的任何其他图像时,我具有不规则的拇指线,其中垂直图像占据宽度并且较大的图像高于其他图像。如何在不裁剪图像的情况下获得相同高度和宽度的拇指?或者只是裁剪一下以适应垂直方向?

我在这里搜索了很多,我发现了一些有用的脚本,但都没有达到目标。

4 个答案:

答案 0 :(得分:1)

我喜欢jQuery NailThumb。它非常可定制且易于使用。

答案 1 :(得分:0)

您可以使用jQuery指定每个图像的宽度/高度。循环遍历<li>元素,获取每个图像的宽高比,为每个图像设置相同的高度,并根据宽高比设置为。

答案 2 :(得分:0)

您可以将图像指定为背景,然后使用CCS3背景尺寸:封面使其完美地填充拇指。然后使用IE过滤器向后兼容。

本文最好地解释了: http://css-tricks.com/perfect-full-page-background-image/

这不需要任何JavaScript。

答案 3 :(得分:0)

试试我在这里提到的这个简单功能:https://stackoverflow.com/a/14731922/382536

/**
* Conserve aspect ratio of the orignal region. Useful when shrinking/enlarging
* images to fit into a certain area.
*
* @param {Number} srcWidth Source area width
* @param {Number} srcHeight Source area height
* @param {Number} maxWidth Fittable area maximum available width
* @param {Number} maxHeight Fittable area maximum available height
* @return {Object} { width, heigth }
*/
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {

    var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);

    return { width: srcWidth*ratio, height: srcHeight*ratio };
}