user10953332
user10953332

Reputation:

Python Pillow:Load Image with data

I need to know how to load image with its data
I use base64 module to read the data

print(base64.b64encode(open('FILENAME','rb').read()))

which gives me the image's data
I need something like

img=Load(imgdata)  #instead of Image.open()

Upvotes: 3

Views: 3462

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207405

Here's how to base64 encode a JPEG/PNG, or any other representation of an image:

import base64

# Base64 encode a PNG/JPEG image
b64 = base64.b64encode(open('image.png','rb').read())

And here's how to decode and get your image back:

import io
from PIL import Image

# Base64 decode and convert from PNG/JPEG to PIL Image
im = Image.open(io.BytesIO(base64.b64decode(b64))) 

As an alternative, if you were using OpenCV, you might want to get back a Numpy array that OpenCV uses for image processing, in which case you could do:

import cv2

NumpyIM = cv2.imdecode(np.asarray(bytearray(base64.b64decode(b64))),0) 

Note that this would have the blue and green channels interchanged vis-à-vis PIL/Pillow, i.e. BGR vs RGB.


Keywords: OpenCV, PIL, Pillow, Python, image processing, base64 encoded, encoding, decoding, decoded, imencode, imdecode, BytesIO, io.BytesIO.

Upvotes: 5

Related Questions