PIL: Convert Bytearray to Image
If you manipulate with bytearrays
, then you have to use io.BytesIO
. Also you can read a file directly to a bytearray
.
import os
import io
import PIL.Image as Image
from array import array
def readimage(path):
count = os.stat(path).st_size / 2
with open(path, "rb") as f:
return bytearray(f.read())
bytes = readimage(path+extension)
image = Image.open(io.BytesIO(bytes))
image.save(savepath)
Open PIL image from byte file
You can try this:
image = Image.frombytes('RGBA', (128,128), image_data, 'raw')
Source Code:def frombytes(mode, size, data, decoder_name="raw", *args):
param mode: The image mode.
param size: The image size.
param data: A byte buffer containing raw data for the given mode.
param decoder_name: What decoder to use.
Convert PIL Image to byte array?
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.
How to convert byte array to image in python
You can generate a bytearray
of dummy data representing a gradient like this:
import numpy as np
# Generate a left-right gradient 242 px wide by 266 pixels tall
ba = bytearray((np.arange(242) + np.zeros((266,1))).astype(np.uint8))
For reference, that array will contain data like this:
array([[ 0., 1., 2., ..., 239., 240., 241.],
[ 0., 1., 2., ..., 239., 240., 241.],
[ 0., 1., 2., ..., 239., 240., 241.],
...,
[ 0., 1., 2., ..., 239., 240., 241.],
[ 0., 1., 2., ..., 239., 240., 241.],
[ 0., 1., 2., ..., 239., 240., 241.]])
And then make into a PIL/Pillow image like this:
from PIL import Image
# Convert bytearray "ba" to PIL Image, 'L' just means greyscale/lightness
im = Image.frombuffer('L', (242,266), ba, 'raw', 'L', 0, 1)
Then you can save the image like this:
im.save('result.png')
Documentation is here.
How to get image from bytes in Python?
Use the PIL module. More information in answers here: Decode image bytes data stream to JPEG
from PIL import Image
from io import BytesIO
with open('img.jpg', 'rb') as f:
data = f.read()
# Load image from BytesIO
im = Image.open(BytesIO(data))
# Display image
im.show()
# Save the image to 'result.FORMAT', using the image format
im.save('result.{im_format}'.format(im_format=im.format))
Python PIL bytes to Image
That image is not formed of raw bytes - rather it is an encoded JPEG file.
Moreover, you are not parsing the ascii HEX representation of the stream into proper bytes:
that is, an "ff" sequence in that file is being passed to PIL as two c letters "f" instead of a byte with the number 255.
So, first, you decode the string to a proper byte sequence - sorry for the convolution - it is likely there is a better way to do that, but I am on a slow day:
data = urllib.urlopen("http://pastebin.ca/raw/2311595").read()
r_data = "".join(chr(int(data[i:i+2],16)) for i in range(0, len(data),2))
Ah, C.Y. posted on hte comment - this way:
>>> import binascii
>>> b_data = binascii.unhexlify(data)
And now, you import it to PIL as a JPEG image:
>>> from PIL import Image
>>> import cStringIO as StringIO
>>> stream = StringIO.StringIO(b_data)
>>> img = Image.open(stream)
>>> img.size
(320, 240)
Related Topics
Standard Way to Embed Version into Python Package
Python Method for Reading Keypress
How to Use Opencv's Connectedcomponentswithstats in Python
How to Pass Extra Arguments to a Python Decorator
Product Code Looks Like Abcd2343, How to Split by Letters and Numbers
Re.Findall Not Returning Full Match
"Unorderable Types: Int() < Str()"
Difference Between Static Static_Url and Static_Root on Django
How to Convert a String to Utf-8 in Python
How to Use Brew Installed Python as the Default Python
Update Row Values Where Certain Condition Is Met in Pandas
How Does the Key Argument in Python's Sorted Function Work
Remove Namespace and Prefix from Xml in Python Using Lxml