PHP resize an image without saving a file
I have images that are displayed as thumbnails on my site. The size of thumbnails varies a lot. Ideally, I would not have to save a copy of each photo in each thumbnail's dimensions. Rather, I could specify in PHP the final dimensions, and have the image resized before it is sent from the server.
I am not trying to resize a photo when it is being uploaded to the server. I am not able to save an image as each thumbnails size.
The issue is that the thumbnails vary in size depending the pages layout. So if I save the image as each thumbnail size, I will save about 20x the number of photos I have.
I have tried saving a 'small' 'medium' and 'large' image, and then I call the one which is closest to the thumbnail size. Seemed a bit crude, but it sounds like this may be the proper method.
Well, as you don't want to exhaust you disk space, you will exhaust your CPU resources, which is much worse.
Even if you think that you're unable to save thumbnails on the disk, you'll have to. There is no other way. You'd just waste your time and eventually turn to proper setup.
我做了类似的事情,你可以做的就是这样的事情,就像之前发布的一样,这可能会占用大量资源,并且保存到磁盘通常会更好,但是如果你真的想这样做,可以尝试一下:
<?php
function createThumbnail($filename, $thumbWidth){
$details = getimagesize($filename);
$content = file_get_contents($filename);
$srcImg = imagecreatefromstring($content);
$thumbHeight = $details[1] * ($thumbWidth / $details[0]);
$thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $details[0], $details[1]);
imagejpeg($thumbImg, null, 100);
imagedestroy($srcImg);
return $thumbImg;
}
header("Content-Type: image/jpeg");
echo createThumbnail("/path/to/image.jpg", 200);
The best way to do this would be of course to calculate image sizes and return img
tags with appropriate attributes like this:
"<img width="" . $width . "px" height="" . $height . "" src="..."/>"
Resizing images "on the fly" is just too time consuming. Consider the case where you show 20 images each one would be scaled consuming 150ms (depending on the size of the image and scale factor). This will be approximately over 3 seconds to display a single page. Do you really want to force users to wait such a long period of time to see the contents of the page?
链接地址: http://www.djcxy.com/p/61150.html上一篇: PHP允许图像上传旋转耗尽内存大小
下一篇: PHP在不保存文件的情况下调整图像大小