Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert base64 string to image and save

Tags:

python

base64

I am trying to convert base64 image data into image file and to save it.

base64_image_str = request.POST.get('base64_image_str')
# it is smthg like: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDA......."

with open("newimage.png", "wb") as f:
    f.write(base64_image_str.decode('base64'))
    f.close()

also tried:

f = open("newimage.png", "wb")
f.write(decodestring(base64_image_str))
f.close()

Image is being saved but it is corrupt and cannot open it. What am I doing wrong?

like image 588
doniyor Avatar asked Dec 19 '22 08:12

doniyor


1 Answers

The start of the string, up to the first comma, is information added by POSTing the data, and as such is not part of the base64 encoding of your file. So remove it before decoding.

like image 108
Scott Hunter Avatar answered Jan 04 '23 10:01

Scott Hunter