如何在Python中进行JPEG压缩而无需写入/读取

问题描述 投票:0回答:3

我想直接使用压缩的 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 版本?

python image jpeg python-imaging-library
3个回答
20
投票

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

StringIO
。 看看:

from io import StringIO # "import StringIO" directly in python2
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%。


11
投票

使用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,参考:Python3 中的 StringIO


0
投票

截至2024年1月,你可以像这样实现你想要的(@Sam Gammon的答案的更新版本,使用Python 3.9测试):

from io import BytesIO

from PIL import Image

img = Image.open("test.jpg")

buffer = BytesIO()
img.save(buffer, "JPEG", quality=10)

with open("./test_quality_10.jpg", "wb") as handle:
    handle.write(buffer.getbuffer())
© www.soinside.com 2019 - 2024. All rights reserved.