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

时间:2017-12-23 08:02:29

标签: image python-3.x flask base64

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

  

binascii.Error:填充不正确

另外,我看看这个StackOverflow问题但是没有用 Convert string in base64 to image and save on filesystem in Python

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

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

我收到此错误

  

返回binascii.a2b_base64(s)

我得到的是来自客户端的这种格式:

  

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

从客户端我发送此请求

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

在我的python代码中,我有这个方法来读取和保存base64图像

@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))

1 个答案:

答案 0 :(得分: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文件扩展名保存它们很奇怪。