Convert base64 string to image and save

I am trying to convert base64 image data to image file and 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()

      

The image is saved, but it is damaged and cannot open it. What am I doing wrong?

+3


source to share


2 answers


The beginning of the line before 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.



+5


source


As you can see, the real image data starts with a comma, you have to remove the rest,



base64_image_str = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDA......."

base64_image_str = base64_image_str[base64_image_str.find(",")+1:]

      

+3


source







All Articles