简体   繁体   English

将base64字符串转换为图像并保存

[英]Convert base64 string to image and save

I am trying to convert base64 image data into image file and to save it. 我试图将base64图像数据转换为图像文件并保存。

base64_image_str = request.POST.get('base64_image_str')
# it is smthg like: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDA......."

with open("newimage.png", "wb") as f:
    f.write(base64_image_str.decode('base64'))
    f.close()

also tried: 还尝试过:

f = open("newimage.png", "wb")
f.write(decodestring(base64_image_str))
f.close()

Image is being saved but it is corrupt and cannot open it. 图像正在保存,但它已损坏,无法打开它。 What am I doing wrong? 我究竟做错了什么?

The start of the string, up to the first comma, is information added by POSTing the data, and as such is not part of the base64 encoding of your file. 字符串的开头,直到第一个逗号,是通过POST数据添加的信息,因此不是文件的base64编码的一部分。 So remove it before decoding. 所以在解码前删除它。

As you see, the real image data starts off by a comma, you should strip off the remaining part, 如您所见,真实图像数据以逗号开头,您应该去掉其余部分,

base64_image_str = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDA......."

base64_image_str = base64_image_str[base64_image_str.find(",")+1:]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM