如何在python flask服务器中保存base64镜像

问题描述 投票:1回答:1

我尝试保存来自HTTP post请求的base64图像字符串,出于某种原因,我得到了多个不同的错误

binascii.Error:填充不正确

此外,我看看这个StackOverflow问题,但不工作Convert string in base64 to image and save on filesystem in Python

但最后,我得到一个0字节的png文件

我的问题是如何在我的服务器文件系统上保存base64字符串图像

I get this error

return binascii.a2b_base64(s)

What I get is this format from the client side:

数据:图像/ JPEG; BASE64,/ 9J / 4AAQSkZJRgABAQEASABIAAD / 2wCEAAICAgICAgMCAgMFAwMDBQYFBQUFBggGBgYGBggKCAgIC ..... AgICgoKC / vuJ91GM9en4hT / AI3TLT8PoqYVw //ž

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))
image python-3.x flask base64
1个回答
6
投票

在执行base64.decodebytes(string)时会出错,因为你的变量string总是等于b'{b64_string}'。它只有不在Base64字母表中的字符。

你可以使用类似的东西:

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

此外,您发送JPEG文件并使用PNG文件扩展名保存它们很奇怪。

© www.soinside.com 2019 - 2024. All rights reserved.