Encoding an image file with base64 Encoding an image file with base64 python python

Encoding an image file with base64


I'm not sure I understand your question. I assume you are doing something along the lines of:

import base64with open("yourfile.ext", "rb") as image_file:    encoded_string = base64.b64encode(image_file.read())

You have to open the file first of course, and read its contents - you cannot simply pass the path to the encode function.

Edit:Ok, here is an update after you have edited your original question.

First of all, remember to use raw strings (prefix the string with 'r') when using path delimiters on Windows, to prevent accidentally hitting an escape character. Second, PIL's Image.open either accepts a filename, or a file-like (that is, the object has to provide read, seek and tell methods).

That being said, you can use cStringIO to create such an object from a memory buffer:

import cStringIOimport PIL.Image# assume data contains your decoded imagefile_like = cStringIO.StringIO(data)img = PIL.Image.open(file_like)img.show()


The first answer will print a string with prefix b'.That means your string will be like this b'your_string' To solve this issue please add the following line of code.

encoded_string= base64.b64encode(img_file.read())print(encoded_string.decode('utf-8'))


import base64from PIL import Imagefrom io import BytesIOwith open("image.jpg", "rb") as image_file:    data = base64.b64encode(image_file.read())im = Image.open(BytesIO(base64.b64decode(data)))im.save('image1.png', 'PNG')