【发布时间】:2014-02-03 04:08:31
【问题描述】:
以facebook画廊为例。我先有一个拇指图像,然后当用户单击它时,会显示图像预览,其中包含大图像。我是否应该为拇指图像和大图像保存图像,然后通过不同的文件访问它,或者只使用原始图像并使用 html 宽度和高度控制其大小,但我想让图像具有其原始大小比例和 ,但最大高度或宽度不能超过我的容器高度或宽度。
【问题讨论】:
以facebook画廊为例。我先有一个拇指图像,然后当用户单击它时,会显示图像预览,其中包含大图像。我是否应该为拇指图像和大图像保存图像,然后通过不同的文件访问它,或者只使用原始图像并使用 html 宽度和高度控制其大小,但我想让图像具有其原始大小比例和 ,但最大高度或宽度不能超过我的容器高度或宽度。
【问题讨论】:
你可以同时使用这两种方法:
<img src="<path_to_full_image>" onclick="show_full(this)" /> + css 调整图像大小以适合您的容器或
<a href="<path_to_full_image>" onclick="show_full(this)"><img src="<path_to_thumb>" /></a>
函数永远是这样的
function show_full(image) {
// now image variable is your image or link
var full_image_ path = this.getAttribute('src');
// for <img> tag
var full_image_ path = this.getAttribute('href');
// for link
// now you have path to full image and can insert it in popup or anywhere else
}
当然,您必须先生成缩略图并将其存储在某个地方,第二种方式会更快,因为浏览器必须加载较小重量的图像
【讨论】:
如果您使用一张图像并将其作为缩略图,则您的缩略图将需要更长的时间来加载,因为它是完整的图像文件。这就是我们使用较小分辨率图像作为缩略图的原因。您可以编写自己的函数来生成缩略图或具有所需高度和宽度的原始图像。
看看这个tread 它展示了如何在 php 中编写缩略图生成器函数。
Facebook 通过 ajax 加载完整的大图,只有当你点击缩略图并在剧院(模态)模式下打开它时。
底线:最好创建原始全长图像的缩略图,并将其存储为不同的文件。这有助于更快地加载图库页面,因为它只有低分辨率拇指,并在点击时加载全长图像。
编辑 发现这段代码是用 php 编写的,用于创建图像的缩略图,
<?php
function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth )
{
// open the directory
$dir = opendir( $pathToImages );
// loop through it, looking for any/all JPG files:
while (false !== ($fname = readdir( $dir ))) {
// parse path for the extension
$info = pathinfo($pathToImages . $fname);
// continue only if this is a JPEG image
if ( strtolower($info['extension']) == 'jpg' || strtolower($info['extension']) == 'jpeg' )
{
echo "Creating thumbnail for {$fname} <br />";
// load image and get image size
$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save thumbnail into a file
imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
}
}
// close the directory
closedir( $dir );
}
// call createThumb function and pass to it as parameters the path
// to the directory that contains images, the path to the directory
// in which thumbnails will be placed and the thumbnail's width.
// We are assuming that the path will be a relative path working
// both in the filesystem, and through the web for links
createThumbs("upload/","upload/thumbs/",100);
?>
【讨论】: