如何在不写/读的情况下在 Python 中执行 JPEG 压缩

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30771652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:57:22  来源:igfitidea点击:

How to perform JPEG compression in Python without writing/reading

pythonimagejpegpillow

提问by user1245262

I'd like to work directly with compressed JPEG images. I know that with PIL/Pillow I can compress an image when I save it, and then read back the compressed image - e.g.

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

but, I'd like a way to do this without the extraneous write and read. Is there some Python package with a function that will take an image and quality number as inputs and return a jpeg version of that image with the given quality?

但是,我想要一种无需额外读写的方法。是否有一些带有函数的 Python 包可以将图像和质量数字作为输入并返回具有给定质量的该图像的 jpeg 版本?

采纳答案by sgammon

For in-memory file-like stuff, you can use StringIO. Take a look:

对于类似内存文件的内容,您可以使用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())

If you check the photo-quality10.jpgfile, it should be the same image, but with 10% quality as the JPEG compression setting.

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

回答by Super Engine

Using BytesIO

使用 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

StringIO is missing in Python3.0, ref to : StringIO in python3

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