【发布时间】:2018-06-05 15:50:30
【问题描述】:
我尝试保存来自 HTTP 发布请求的 base64 图像字符串,但由于某种原因,我收到多个不同的错误
binascii.Error: 不正确的填充
另外,我查看了这个 StackOverflow 问题,但没有工作 Convert string in base64 to image and save on filesystem in Python
但最后,我得到了一个 0 字节的 png 文件
我的问题是如何在我的服务器文件系统上保存 base64 字符串图像
我收到此错误
返回 binascii.a2b_base64(s)
我从客户端得到的是这种格式:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wCEAAICAgICAgMCAgMFAwMDBQYFBQUFBggGBgYGBggKCAgIC.....AgICgoKC/vuJ91GM9en4hT/AI3TLT8PoqYVw//Z
我从客户端发送这个请求
{
"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))
【问题讨论】:
标签: image python-3.x flask base64