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

不幸的是,这是JPEG压缩的一个特性,并且没有严格的反函数(如果您想要大规模的效率,可以用数学方法计算)。在

但是,您可以低效地强行进行计算,并使用以下方法使其接近。如果您不想要相同的尺寸,只需将质量更改为比例因子,它的工作原理应该类似。在from PIL import Image

import os

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 = 100 #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.replace(".jpg","_c.jpg"))

print("Error: File cannot be compressed below this size")

break

compress_pic(file_path, quality)

current_size = os.stat(file_path.replace(".jpg","_c.jpg")).st_size

quality -= 1

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(filepath)

dim = picture.size

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

newsize = os.stat(os.path.join(os.getcwd(),"Compressed_"+file)).st_size

return new_size

您的文件应该以_c结尾保存。如果没有,则说明文件已经足够小,或者无法进一步压缩。在

你可能感兴趣的:(python图片压缩限定大小)