如何使用PIL减少图像文件大小 [英] How to reduce the image file size using PIL

查看:477
本文介绍了如何使用PIL减少图像文件大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用PIL通过将较大的图像转换为较小的图像来调整图像大小。有没有任何标准的方法来减少图像的文件大小,而不会失去质量太多,让说图像的原始大小是100KB,我想得到它像5或10 KB,尤其是png和jpeg格式。

I am using PIL to resize the images there by converting larger images to smaller ones. Are there any standard ways to reduce the file size of the image without losing the quality too much, lets say the original size of the image is 100KB, i want to get it down to like 5 or 10 KB especially for png and jpeg formats.

推荐答案

用于保存JPEG和PNG的内置参数是优化的。

A built-in parameter for saving JPEGs and PNGs is optimize.

 # My image is a 200x374 jpeg that is 102kb large
 >>> foo = Image.open("path\\to\\image.jpg")
 >>> foo.size
  (200,374)
 # I downsize the image with an ANTIALIAS filter (gives the highest quality)
 >>> foo = foo.resize((160,300),Image.ANTIALIAS)
 >>> foo.save("path\\to\\save\\image_scaled.jpg",quality=95)
 # The saved downsized image size is 24.8kb
 >>> foo.save("path\\to\\save\\image_scaled_opt.jpg",optimize=True,quality=95)
 # The saved downsized image size is 22.9kb

optimize标志将对图像执行额外的传递,以尽可能减少其大小。 1.9kb看起来可能不太多,但是上百/上千张图片,它可以加起来。

The optimize flag will do an extra pass on the image to find a way to reduce it's size as much as possible. 1.9kb might not seem like much, but over hundreds/thousands of pictures, it can add up.

现在尝试将其缩小到5kb到10kb,您可以更改保存选项中的质量值。
在这种情况下使用85的质量而不是95将产生:
未优化:15.1kb
优化:14.3kb
使用质量75(默认如果参数被省略)将产生:
未优化:11.8kb
优化:11.2kb

Now to try and get it down to 5kb to 10 kb, you can change the quality value in the save options. Using a quality of 85 instead of 95 in this case would yield: Unoptimized: 15.1kb Optimized : 14.3kb Using a quality of 75 (default if argument is left out) would yield: Unoptimized: 11.8kb Optimized : 11.2kb

我喜欢质量85与优化,因为质量不会影响太多,文件大小要小得多。

I prefer quality 85 with optimize because the quality isn't affect much, and the file size is much smaller.

这篇关于如何使用PIL减少图像文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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