Python 将 PIL 图像转换为字节数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33101935/
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
Convert PIL Image to byte array?
提问by Evelyn Jeba
I have an image in PIL Image format. I need to convert it to byte array.
我有一个 PIL Image 格式的图像。我需要将其转换为字节数组。
img = Image.open(fh, mode='r')
roiImg = img.crop(box)
Now I need the roiImg
as a byte array.
现在我需要roiImg
一个字节数组。
采纳答案by Evelyn Jeba
Thanks everyone for your help.
感谢大家的帮助。
Finally got it resolved!!
终于解决了!!
import io
img = Image.open(fh, mode='r')
roiImg = img.crop(box)
imgByteArr = io.BytesIO()
roiImg.save(imgByteArr, format='PNG')
imgByteArr = imgByteArr.getvalue()
With this i don't have to save the cropped image in my hard disc and I'm able to retrieve the byte array from a PIL cropped image.
有了这个,我不必将裁剪后的图像保存在我的硬盘中,我可以从 PIL 裁剪后的图像中检索字节数组。
回答by Nori
This is my solution.Please use this function.
这是我的解决方案。请使用此功能。
from PIL import Image
import io
def image_to_byte_array(image:Image):
imgByteArr = io.BytesIO()
image.save(imgByteArr, format=image.format)
imgByteArr = imgByteArr.getvalue()
return imgByteArr
回答by Chris Ivan
I think you can simply call the PIL image's .tobytes()
method, and from there, to convert it to an array, use the bytes
built-in.
我认为您可以简单地调用 PIL 图像的.tobytes()
方法,然后从那里将其转换为数组,使用bytes
内置的。
#assuming image is a flattened, 3-channel numpy array of e.g. 600 x 600 pixels
bytesarray = bytes(Image.fromarray(array.reshape((600,600,3))).tobytes())