How to save base64 image in python flask server

15,942

You get error when doing base64.decodebytes(string) because your variable string is always equal to b'{b64_string}'. And it just has characters which are not in Base64 alphabet.

You could use something like:

def convert_and_save(b64_string):
    with open("imageToSave.png", "wb") as fh:
        fh.write(base64.decodebytes(b64_string.encode()))

Moreover, it's strange that you send JPEG files and save them with PNG filename extension.

Share:
15,942
George C.
Author by

George C.

Nothing special to see but you can find something interesting here

Updated on June 14, 2022

Comments

  • George C.
    George C. almost 2 years

    I try to save a base64 image string that comes from HTTP post request and for some reason, I get multiple different errors

    binascii.Error: Incorrect padding

    Also, i look at this StackOverflow question but is not working Convert string in base64 to image and save on filesystem in Python

    but in the end, I get a png file that is 0 bytes

    My question is how I can save a base64 string image on my server filesystem

    I get this error

    return binascii.a2b_base64(s)

    What I get is this format from the client side:

    data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wCEAAICAgICAgMCAgMFAwMDBQYFBQUFBggGBgYGBggKCAgIC.....AgICgoKC/vuJ91GM9en4hT/AI3TLT8PoqYVw//Z

    From the client side I send this request

    {
          "img" : "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wCEAAICAgICAgMCAgMFAwMDBQYFBQUFBggGBgYGBggKCAgIC.....AgICgoKC/vuJ91GM9en4hT/AI3TLT8PoqYVw//Z"
    }
    

    in my python code, I have this method to read and save the base64 image

    @app.route('/upload', methods=['POST']) 
    def upload_base64_file(): 
        """ 
            Upload image with base64 format and get car make model and year 
            response 
        """
    
      data = request.get_json()
      # print(data)
    
      if data is None:
          print("No valid request body, json missing!")
          return jsonify({'error': 'No valid request body, json missing!'})
      else:
    
          img_data = data['img']
    
          # this method convert and save the base64 string to image
          convert_and_save(img_data)
    
    
    
    
    def convert_and_save(b64_string):
    
        b64_string += '=' * (-len(b64_string) % 4)  # restore stripped '='s
    
        string = b'{b64_string}'
    
        with open("tmp/imageToSave.png", "wb") as fh:
            fh.write(base64.decodebytes(string))
    
  • mosnoi ion
    mosnoi ion about 6 years
    got error: AttributeError: 'module' object has no attribute 'decodebytes'
  • Andriy Makukha
    Andriy Makukha about 6 years
    @mosnoiion, in Python 2 you need to use base64.b64decode() instead of base64.decodebytes().