如何在没有编写/阅读的情况下在Python中执行JPEG压缩

时间:2015-06-11 04:35:01

标签: python image jpeg pillow

我想直接使用压缩的JPEG图像。我知道使用PIL / Pillow我可以在保存时压缩图像,然后回读压缩图像 - 例如

from PIL import Image
im1 = Image.open(IMAGE_FILE)
IMAGE_10 = os.path.join('./images/dog10.jpeg')
im1.save(IMAGE_10,"JPEG", quality=10)
im10 = Image.open(IMAGE_10)

但是,我想要一种方法来做到这一点,而无需无关的写入和读取。是否有一些Python软件包带有一个函数,它将图像和质量数作为输入,并以给定的质量返回该图像的jpeg版本?

2 个答案:

答案 0 :(得分:7)

对于内存中类似文件的内容,您可以使用StringIO。 看看:

import StringIO
from PIL import Image
im1 = Image.open(IMAGE_FILE)

# here, we create an empty string buffer    
buffer = StringIO.StringIO()
im1.save(buffer, "JPEG", quality=10)

# ... do something else ...

# write the buffer to a file to make sure it worked
with open("./photo-quality10.jpg", "w") as handle:
    handle.write(buffer.contents())

如果您检查photo-quality10.jpg文件,它应该是相同的图像,但JPEG压缩设置的质量为10%。

答案 1 :(得分:2)

使用BytesIO

try:
    from cStringIO import StringIO as BytesIO
except ImportError:
    from io import BytesIO

def generate(self, image, format='jpeg'):
    im = self.generate_image(image)
    out = BytesIO()
    im.save(out, format=format,quality=75)
    out.seek(0)
    return out

Python3.0中缺少StringIO,参考:StringIO in python3