Python图像库(PIL),如何将图像压缩成所需的文件大小? [英] Python image library (PIL), how to compress image into desired file size?

查看:5828
本文介绍了Python图像库(PIL),如何将图像压缩成所需的文件大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要压缩任何上传的图片小于500kb的文件大小,我在google上搜索,我可以看到是:

I got a requirement to compress any uploaded images less than 500kb in file size, I have searched on google and all I can see is:

 >>> foo = foo.resize((160,300),Image.ANTIALIAS)
 >>> foo.save("path\\to\\save\\image_scaled.jpg",quality=95)

如果我采用这种方法,我将不得不检查图像是否压缩后小于500kb,如果不是那么去低质量和大小。

If I go with this approach I will have to check if the image is less than 500kb after compress, if not then go for lower quality and size.

有更好的方法吗?

推荐答案

JPEG压缩是不可预测的。你描述的方法,压缩&测量&请再试一次,这是我知道的唯一方法。

JPEG compression is not predictable beforehand. The method you described, compress & measure & try again, is the only way I know.

您可以尝试使用不同的质量设置压缩大量典型图像,以了解最佳起点,方式猜测如何更改设置将影响大小。

You can try compressing a number of typical images with different quality settings to get an idea of the optimum starting point, plus a way of guessing how changes to the setting will affect the size. That will get you to zero in on the optimum size without too many iterations.

您还可以将类似文件的对象传递给 save 函数,不打扰写入磁盘,只计算字节。一旦你确定了最好的设置,然后你可以再次保存到一个实际的文件。

You can also pass a file-like object to the save function that doesn't bother to write to disk, just counts the bytes. Once you've determined the best settings then you can save it again to an actual file.

编辑:这里是一个合适的字节计数文件对象的实现。只需在保存后检查 size

Here's an implementation of a suitable byte counting file object. Just check size after the save.

class file_counter(object):
    def __init__(self):
        self.position = self.size = 0

    def seek(self, offset, whence=0):
        if whence == 1:
            offset += self.position
        elif whence == 2:
            offset += self.size
        self.position = min(offset, self.size)

    def tell(self):
        return self.position

    def write(self, string):
        self.position += len(string)
        self.size = max(self.size, self.position)

编辑2:这是一个二进制搜索使用上述获得最小的质量在最小的尝试次数。

Edit 2: Here's a binary search using the above to get the optimal quality in the smallest number of attempts.

def smaller_than(im, size, guess=70, subsampling=1, low=1, high=100):
    while low < high:
        counter = file_counter()
        im.save(counter, format='JPEG', subsampling=subsampling, quality=guess)
        if counter.size < size:
            low = guess
        else:
            high = guess - 1
        guess = (low + high + 1) // 2
    return low

这篇关于Python图像库(PIL),如何将图像压缩成所需的文件大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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