【问题标题】:Compress image quality (from 4MB to 2MB) without losing its dimension在不丢失尺寸的情况下压缩图像质量(从 4MB 到 2MB)
【发布时间】:2015-07-23 10:31:44
【问题描述】:

我正在尝试使用ImageMagick 对图像进行compress the quality。我的意思是我有一个尺寸为1600X800 且大小为4MB 的图像。现在我试图在不调整其尺寸的情况下将此图像的质量压缩为2MB,这意味着新生成的图像也与实际图像(i.e. 1600X800)具有相同的尺寸,但此图像的质量应压缩为2MBhalf of the actual image)。为此,现在我使用下面的代码,但这不是压缩新创建的图像的大小:

$src_img = "src.png";
$dest_img = "dest.png";
exec("convert $src_img -quality 90 $dest_img");

那么任何人都可以告诉我如何使用ImageMagick 压缩图像的大小而不会丢失其实际尺寸?

【问题讨论】:

    标签: php image imagemagick


    【解决方案1】:

    尝试使用 ImageMagick 并定义您想要的最大输出大小(以 kB 为单位)并让它降低质量直到达到该大小:

    convert input.jpg -define jpeg:extent=2000k output.jpg
    

    例如,如果我创建一个 2000x2000 的噪声图像,像这样

    convert -size 2000x2000 xc:gray +noise gaussian input.jpg
    

    我得到这个 4MB 的文件。

    -rw-r--r--@  1 mark  staff    4175639 12 May 15:40 input.jpg
    

    如果我使用上面的命令来减小文件大小

    convert input.jpg -define jpeg:extent=2000k output.jpg
    

    我得到了这个 1.9MB 的文件

    -rw-r--r--   1 mark  staff    1933708 12 May 15:41 output.jpg
    

    但它的像素尺寸在 2000x2000 时保持不变

    identify output.jpg
    
    output.jpg JPEG 2000x2000 2000x2000+0+0 8-bit sRGB 1.934MB 0.000u 0:00.000
    

    只是为了好玩,您可以看到设置不同的文件大小如何改变质量设置:

    convert input.jpg -define jpeg:extent=2000k output.jpg <--- 2MB file => 82 quality
    identify -verbose output.jpg | grep -i quality
    Quality: 82
    
    convert input.jpg -define jpeg:extent=1000k output.jpg <--- 1MB file => 65 quality
    identify -verbose output.jpg | grep -i quality
    Quality: 65
    
    convert input.jpg -define jpeg:extent=500k output.jpg <--- 500kB file => 38 quality
    identify -verbose output.jpg | grep -i quality
    Quality: 38
    

    如果你想用 Python 做类似的事情,我写了一个很好的答案here。它对满足最大尺寸要求的 JPEG 质量进行二分搜索。

    【讨论】:

      【解决方案2】:

      您可以使用 GD 库函数更改图像质量。它比使用exec() 更安全。

      $im = imagecreatefrompng("src.png");
      
      imagepng($im, 'dest.png', $quality);
      imagedestroy($im);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-07
        • 1970-01-01
        • 1970-01-01
        • 2019-12-13
        • 1970-01-01
        • 2014-04-24
        • 2021-06-25
        相关资源
        最近更新 更多