PHP 中有效的 JPEG 图像大小调整 [英] Efficient JPEG Image Resizing in PHP

查看:18
本文介绍了PHP 中有效的 JPEG 图像大小调整的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 PHP 中调整大图像的最有效方法是什么?

What's the most efficient way to resize large images in PHP?

我目前正在使用 GD 函数 imagecopyresampled 来拍摄高分辨率图像,并干净地调整大小它们缩小到适合网页浏览的大小(大约 700 像素宽 x 700 像素高).

I'm currently using the GD function imagecopyresampled to take high resolution images, and cleanly resize them down to a size for web viewing (roughly 700 pixels wide by 700 pixels tall).

这在小照片(小于 2 MB)上效果很好,整个调整大小操作在服务器上不到一秒钟.但是,该网站最终将为上传最大 10 MB 图像(或最大 5000x4000 像素的图像)的摄影师提供服务.

This works great on small (under 2 MB) photos and the entire resize operation takes less than a second on the server. However, the site will eventually service photographers who may be uploading images up to 10 MB in size (or images up to 5000x4000 pixels in size).

对大图像执行这种调整大小操作往往会显着增加内存使用量(较大的图像会使脚本的内存使用量超过 80 MB).有什么方法可以使这种调整大小操作更有效吗?我是否应该使用替代图像库,例如 ImageMagick?

Doing this kind of resize operation with large images tends to increase the memory usage by a very large margin (larger images can spike the memory usage for the script past 80 MB). Is there any way to make this resize operation more efficient? Should I be using an alternate image library such as ImageMagick?

现在,调整大小的代码看起来像这样

Right now, the resize code looks something like this

function makeThumbnail($sourcefile, $endfile, $thumbwidth, $thumbheight, $quality) {
    // Takes the sourcefile (path/to/image.jpg) and makes a thumbnail from it
    // and places it at endfile (path/to/thumb.jpg).

    // Load image and get image size.
    $img = imagecreatefromjpeg($sourcefile);
    $width = imagesx( $img );
    $height = imagesy( $img );

    if ($width > $height) {
        $newwidth = $thumbwidth;
        $divisor = $width / $thumbwidth;
        $newheight = floor( $height / $divisor);
    } else {
        $newheight = $thumbheight;
        $divisor = $height / $thumbheight;
        $newwidth = floor( $width / $divisor );
    }

    // Create a new temporary image.
    $tmpimg = imagecreatetruecolor( $newwidth, $newheight );

    // Copy and resize old image into new image.
    imagecopyresampled( $tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );

    // Save thumbnail into a file.
    imagejpeg( $tmpimg, $endfile, $quality);

    // release the memory
    imagedestroy($tmpimg);
    imagedestroy($img);

推荐答案

人们说 ImageMagick 的速度要快得多.充其量只是比较两个库并对其进行衡量.

People say that ImageMagick is much faster. At best just compare both libraries and measure that.

  1. 准备 1000 张典型图像.
  2. 写两个脚本——一个给 GD,一个给用于 ImageMagick.
  3. 运行它们几次.
  4. 比较结果(总执行时间、CPU 和 I/O 使用率、结果图像质量).

其他人最好的东西,对你来说却不一定是最好的.

Something which the best everyone else, could not be the best for you.

另外,在我看来,ImageMagick 有更好的 API 接口.

Also, in my opinion, ImageMagick has much better API interface.

这篇关于PHP 中有效的 JPEG 图像大小调整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆