简体   繁体   English

将 PIL 图像转换为字节数组?

[英]Convert PIL Image to byte array?

I have an image in PIL Image format.我有一个 PIL Image 格式的图像。 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.现在我需要roiImg作为字节数组。

Thanks everyone for your help.感谢大家的帮助。

Finally got it resolved!!终于解决了!!

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()

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 裁剪后的图像中检索字节数组。

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

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())

Python file read and extract binary array Python文件读取和提取二进制数组

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM