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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With