Convert PIL Image to byte array?

I have an image in PIL Image format. I need to convert it to byte array.

img = Image.open(fh, mode='r')
roiImg = img.crop(box)

Now I need the roiImg as a byte array.

143227 次浏览

Thanks everyone for your help.

终于解决了! !

import io


img = Image.open(fh, mode='r')
roi_img = img.crop(box)


img_byte_arr = io.BytesIO()
roi_img.save(img_byte_arr, format='PNG')
img_byte_arr = img_byte_arr.getvalue()

有了这个,我不必保存在我的硬盘裁剪图像,我能够检索字节数组从 PIL 裁剪图像。

这是我的解决方案。请使用这个函数。

from PIL import Image
import io


def image_to_byte_array(image: Image) -> bytes:
# BytesIO is a fake file stored in memory
imgByteArr = io.BytesIO()
# image.save expects a file as a argument, passing a bytes io ins
image.save(imgByteArr, format=image.format)
# Turn the BytesIO object back into a bytes object
imgByteArr = imgByteArr.getvalue()
return imgByteArr

我认为您可以简单地调用 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())

Python file read and extract binary array

import base64
with open(img_file_name, "rb") as f:
image_binary = f.read()
base64_encode = base64.b64encode(image_binary)
byte_decode = base64_encode.decode('utf8')