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

查看:64
本文介绍了如何使用 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 的内置参数是 optimize.

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

 >>> from PIL import Image
 # 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 its 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 affected much, and the file size is much smaller.

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

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