gpt4 book ai didi

python - 如何使用python PIL库压缩小于限制文件大小的图片?

转载 作者:行者123 更新时间:2023-12-04 14:24:14 24 4
gpt4 key购买 nike

我需要将图片发送到另一个地方,它要求图片大小必须小于 512kb。
我用 PIL处理我从互联网上下载的图片。所以我不知道下一张图片的尺寸是多少,代码如下:

from PIL import Image
picture_location = '/var/picture/1233123.jpg'
compressed_picture_location = '/var/picture/1233123_compressed.jpg'
im = Image.open(picture_location)
quality = 75
im.save(compressed_picture_location, quality=quality)
im.save()

问题是压缩图片的文件大小不是原始图片的75%或75%*75%,所以我必须压缩它,统计它,再次压缩,我无法选择合适的质量值。

有没有其他方法可以解决这个问题?
请帮助或尝试提供一些想法如何实现这一点。

最佳答案

不幸的是,这是 JPEG 压缩的一个属性,并且没有严格的反函数(如果你想要大规模效率,你可以用数学方法计算它)。
但是,您可以低效地强制计算并通过以下方法使其接近。如果您不想要相同的大小,只需将质量更改为比例因子,它的工作方式应该类似。

import os
from PIL import Image

def compress_under_size(size, file_path):
'''file_path is a string to the file to be custom compressed
and the size is the maximum size in bytes it can be which this
function searches until it achieves an approximate supremum'''

quality = 90 #not the best value as this usually increases size

current_size = os.stat(file_path).st_size

while current_size > size or quality == 0:
if quality == 0:
os.remove(file_path)
print("Error: File cannot be compressed below this size")
break

compress_pic(file_path, quality)
current_size = os.stat(file_path).st_size
quality -= 5


def compress_pic(file_path, qual):
'''File path is a string to the file to be compressed and
quality is the quality to be compressed down to'''
picture = Image.open(file_path)
dim = picture.size

picture.save(file_path,"JPEG", optimize=True, quality=qual)

processed_size = os.stat(file_path).st_size

return processed_size

for file in os.listdir("pics"):
try:
pic = f"./pics/{file}"
compress_under_size(10000,pic)
except Exception:
pass

关于python - 如何使用python PIL库压缩小于限制文件大小的图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49124864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com