Vlad de Elstyr Vlad de Elstyr -4 years ago 271
Python Question

In python decode newly created Image to Base64 String

for the past few hours i've been trying to create a Base64 String of an Image, but it won't work.

ship_color = (0,100,100,255)
img = Image.new("RGBA", (100,100))
for i in range(20):
for j in range(20):
img.putpixel((40 + i, 40 + j), ship_color)
img.save("tmp.png", format = "PNG")
im = open("tmp.png", "rb").read()
base = base64.b64encode(im)

When i try to create an image from the String again i get an exception:

img2 = Image.frombytes("RGBA", (100, 100), base)
ValueError: not enough image data

Other online services for Base64 Decoding also give an error, so the base64 String itself does not seem to be correct.

example image String (from open().read()):


example base64 String:


Answer Source

You need to base64 encode before you can decode.

You can achieve this without creating a temporary file by using an in memory file, with io.BytesIO()

in_mem_file = io.BytesIO()
img.save(in_mem_file, format = "PNG")
# reset file pointer to start
img_bytes = in_mem_file.read()

base64_encoded_result = base64.b64encode(img_bytes)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download