How to perform JPEG compression in Python without writing/reading(如何在不写入/读取的情况下在Python中执行JPEG压缩)
本文介绍了如何在不写入/读取的情况下在Python中执行JPEG压缩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想直接处理压缩的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版本?
推荐答案
对于内存中类似文件的内容,可以使用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
文件,它应该是相同的图像,但质量为10%,与JPEG压缩设置相同。
这篇关于如何在不写入/读取的情况下在Python中执行JPEG压缩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何在不写入/读取的情况下在Python中执行JPEG压缩


基础教程推荐
猜你喜欢
- Python 的 List 是如何实现的? 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01