我想用Python减小PNG文件的大小。我在互联网上查阅了很多资料,但是没有找到任何关于如何在不改变图像尺寸(即高度/宽度)的情况下减小图像文件大小的内容。我找到的是如何使用PIL或其他Python库更改图像尺寸的方法。
如何在保持图像尺寸不变的情况下减小图像文件大小呢?
如何在保持图像尺寸不变的情况下减小图像文件大小呢?
compress_level
参数的png写入器。import os
import requests
from PIL import Image
from io import BytesIO
img_url = 'http://pngnq.sourceforge.net/testimages/lena.png'
response = requests.get(img_url)
img = Image.open(BytesIO(response.content))
compress_level=0
编写png:path_uncompressed = './lena_uncompressed.png'
img.save(path_uncompressed,compress_level=0)
print(os.path.getsize(path_uncompressed))
> 691968
第三步:使用compress_level=9
编写PNG文件:path_compressed = './lena_compressed.png'
img.save(path_compressed,compress_level=9)
print(os.path.getsize(path_compressed))
> 406889
在这种情况下,我们得到了可观的30%压缩,没有明显的图像质量降低(这应该是无损压缩算法所期望的)。PNG是一种无损格式,显然会占用更多的空间。
如果你只关心分辨率,那么你可以将它转换为任何有损形式,如JPG。
https://whatis.techtarget.com/definition/lossless-and-lossy-compression
转换后的尺寸将是相同的,但质量取决于所需的压缩程度。
将PNG转换为JPG的代码段:
from PIL import Image
im = Image.open("Picture2.png")
rgb_im = im.convert('RGB')
rgb_im.save('Picture2.jpg')
img.convert("P", palette=Image.ADAPTIVE)