Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 724
Evelyn Jeba Avatar asked Oct 13 '15 11:10

Evelyn Jeba


People also ask

How can I get bytes from image in PIL?

In the above code, we save the im_resize Image object into BytesIO object buf . Note that in this case, you have to specify the saving image format because PIL does not know the image format in this case. The bytes string can be retrieved using getvalue() method of buf variable.

How do you extract bytes of an image in Python?

path. getsize() is a method of the os module that is used to get the size of a specified path. Pass the image path to this function to get the size of the image file in bytes.

What is PIL image in Python?

Python Imaging Library is a free and open-source additional library for the Python programming language that adds support for opening, manipulating, and saving many different image file formats. It is available for Windows, Mac OS X and Linux. The latest version of PIL is 1.1.


2 Answers

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.

like image 106
Evelyn Jeba Avatar answered Oct 11 '22 14:10

Evelyn Jeba


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 
like image 30
Nori Avatar answered Oct 11 '22 12:10

Nori