Python 从字节文件打开 PIL 图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32908639/
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
Open PIL image from byte file
提问by Michael Dorner
I have this imagewith size 128 x 128 pixels and RGBA stored as byte values in my memory. But
我有这个图像大小为 128 x 128 像素和 RGBA 存储在我的内存中的字节值。但
from PIL import Image
image_data = ... # byte values of the image
image = Image.frombytes('RGBA', (128,128), image_data)
image.show()
throws the exception
抛出异常
ValueError: not enough image data
ValueError:没有足够的图像数据
Why? What am I doing wrong?
为什么?我究竟做错了什么?
采纳答案by Marvelous Jie
You can try this:
你可以试试这个:
image = Image.frombytes('RGBA', (128,128), image_data, 'raw')
Source Code:def frombytes(mode, size, data, decoder_name="raw", *args): param mode: The image mode. param size: The image size. param data: A byte buffer containing raw data for the given mode. param decoder_name: What decoder to use.
源代码:def frombytes(mode, size, data, decoder_name="raw", *args): param mode: The image mode. param size: The image size. param data: A byte buffer containing raw data for the given mode. param decoder_name: What decoder to use.
回答by Colonel Thirty Two
The documentation for Image.open
says that it can accept a file-like object, so you should be able to pass in a io.BytesIO
object created from the bytes
object containing the encoded image:
的文档Image.open
说它可以接受类似文件的对象,因此您应该能够传入io.BytesIO
从bytes
包含编码图像的对象创建的对象:
from PIL import Image
import io
image_data = ... # byte values of the image
image = Image.open(io.BytesIO(image_data))
image.show()