问题描述
我正在尝试使用ImageMagick
对图像进行compress the quality
.我的意思是我有一个尺寸为1600X800
且尺寸为4MB
的图像.现在,我尝试将图像的质量压缩为2MB
而不调整其尺寸,这意味着新生成的图像也具有与实际图像(i.e. 1600X800)
相同的尺寸,但应将此图像的质量压缩为2MB
( half of the actual image
).为此,现在我使用下面的代码,但这不会压缩新创建的图像的大小:
I am trying to compress the quality
of an image using ImageMagick
. I mean that I have an image which dimension is 1600X800
and size is 4MB
. Now I am trying to compress the quality of this image into 2MB
without resizing its dimensions, means the newly generated image also have the same dimension as actual image (i.e. 1600X800)
but the quality of this image should be compress into 2MB
(half of the actual image
). For this, now I am using the below code, but this is not compress the size of the newly created image:
$src_img = "src.png";
$dest_img = "dest.png";
exec("convert $src_img -quality 90 $dest_img");
那么任何人都可以告诉我如何使用ImageMagick
压缩图像大小而不丢失实际尺寸吗?
So can anyone please tell me what can I do to compress the size of the image without losing its actual dimension using ImageMagick
?
推荐答案
尝试使用ImageMagick并定义所需的最大输出大小(以kB为单位),直到达到该大小为止都会降低质量:
Try using ImageMagick and defining the maximum output size (in kB) that you want and letting it reduce the quality until that size is achieved:
convert input.jpg -define jpeg:extent=2000k output.jpg
例如,如果我创建一个2000x2000的噪声图像,像这样
For example, if I create a 2000x2000 image of noise, like this
convert -size 2000x2000 xc:gray +noise gaussian input.jpg
我得到了这个4MB的文件.
I get this 4MB file.
-rw-r--r--@ 1 mark staff 4175639 12 May 15:40 input.jpg
如果我使用上面的命令来减小文件大小
If I use the command above to reduce the file size
convert input.jpg -define jpeg:extent=2000k output.jpg
我得到了这个1.9MB的文件
I get this 1.9MB file
-rw-r--r-- 1 mark staff 1933708 12 May 15:41 output.jpg
,但像素尺寸在2000x2000不变.
but its pixel dimensions remain unaltered at 2000x2000
identify output.jpg
output.jpg JPEG 2000x2000 2000x2000+0+0 8-bit sRGB 1.934MB 0.000u 0:00.000
只是为了好玩,您可以看到设置不同的文件大小如何改变质量设置:
Just for fun, you can see how setting different file sizes changes the quality setting:
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进行类似操作的方法,我在此处编写了一个效果很好的答案.它会对满足最大尺寸要求的JPEG质量进行二进制搜索.
If you want a way to do something similar with Python, I wrote an answer that works pretty well here. It does a binary search for a JPEG quality that satisfies a maximum size requirement.
这篇关于压缩图像质量(从4MB到2MB)而不会丢失其尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!