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

时间:2018-03-06 06:45:40

标签: python python-imaging-library

我需要将图片发送到另一个地方,要求图片大小必须小于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%,所以我必须压缩它,统计它,再次压缩,我无法选择合适的质量值。

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

2 个答案:

答案 0 :(得分:1)

当您使用PIL更改质量时,图像的尺寸不会改变,它只是使用JPEG压缩来改变图像的质量。默认情况下,该值为80,因此将值更改为75将不会减小太多大小,您可以将值更改为大约60而不会丢失大量图片质量。该值以对数方式减小,因此如果您想要精确的数学运算,您可以阅读有关JPEG压缩的内容。 https://math.dartmouth.edu/archive/m56s14/public_html/proj/Marcus_proj.pdf

答案 1 :(得分:0)

不幸的是,这是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。如果不是,则意味着该文件已经足够小或者无法进一步压缩。

相关问题