Convert PIL Image to byte array?

PythonImageBytearrayPython Imaging-Library

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

This is my solution. Please use this function.

from PIL import Image
import io

def image_to_byte_array(image: Image) -> bytes:
  imgByteArr = io.BytesIO()
  image.save(imgByteArr, format=image.format)
  imgByteArr = imgByteArr.getvalue()
  return imgByteArr

Solution 3 - Python

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.

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

Solution 4 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEvelyn JebaView Question on Stackoverflow
Solution 1 - PythonEvelyn JebaView Answer on Stackoverflow
Solution 2 - PythonNoriView Answer on Stackoverflow
Solution 3 - PythonChris IvanView Answer on Stackoverflow
Solution 4 - Pythonyelran2003View Answer on Stackoverflow