gpt4 book ai didi

python - 转换数据:image from base64 to JPEG in Python

转载 作者:行者123 更新时间:2023-11-30 22:12:14 24 4
gpt4 key购买 nike

从客户的 POST 提交中,我们成功接收到以下格式的图像:data:image/jpeg;base64,/9j/....,并且正在生成一个图像文件以下代码:

@app.route('/submission', methods=('GET', 'POST'))
def submission():

if request.method == 'POST':

raw_image = request.form['file']
#Problem Starts Here
# this doesn't work either:
# raw_image = raw_image.replace("data:image/jpeg;base64,/9j/", '');
with open(UPLOADED_IMAGES_DEST+'/image.jpeg', 'wb') as fh:
fh.write(base64.decodebytes(raw_image))
#Problem Ends Here
return jsonify(request.form)

return render_template('submission.html')

但是,该图像无法打开,因为它是“无效或不受支持的格式”。我正在尝试改进转换过程,以便生成可查看的 JPEG 图像。

raw_image 的开头:

数据:图像/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQU FBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCADwAUADASIAAhEBAxEB/8QAHQAAAgIDAQEBAAAAAAAAAAAABQYEBwIDCAEAACf/EAEwQAAEDAwMCBAQEAwUFBQQLAAECAxEABAUGEiExQQcTUWEIInGBFDKRoRVCUiOxwdHwJGJyouEJFjOSwh dDgvEmU2ODk7LDxNLU4v/EABsBAAMBAQEBAQAAAAAAAAAAAA...

最佳答案

我获取了你的数据,并对其进行了解码,它看起来非常接近我从真实文件中获取的 JPEG header (下图)。没有看到任何问题,除了您必须从 /9j/4AA... 开始解码。

>>> a = '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCADwAUADASIAAhEBAxEB/8QAHQAAAgIDAQEBAAAAAAAAAAAABQYEBwIDCAEACf/EAEwQAAEDAwMCBAQEAwUFBQQLAAECAxEABAUGEiExQQcTUWEIInGBFDKRoRVCUiOxwdHwJGJyouEJFjOSwhdDgvEmU2ODk7LDxNLU4v/EABsBAAMBAQEBAQAAAAAAAAAA'
>>> base64.b64decode(a)
'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00C\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05

这是我的真实 JPEG 图片的十六进制转储。

enter image description here

您必须删除 data:image/jpeg;base64,,但不要超出范围 - 这会破坏图像数据。

关于python - 转换数据:image from base64 to JPEG in Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51164445/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com