Django的ImageField来自post raw d

2024-05-12 15:17:36 发布

您现在位置:Python中文网/ 问答频道 /正文

< >我将一个原始数据数组(rgBA88 88)从应用程序(C++)发送到在Base64中编码的HTTP的邮政数据中的Django服务器:

field1=value1&prof_img=KSsf134SF38u483y... more bytes ....sdknADdSIU7rb== 

我已经成功地将它从base64解码回原始数据,我做了一些测试,数据得到了正确的转换。在

现在我被困在尝试对这些解码的数据做些什么,这样我就可以把它保存在模型的ImageField中。在

如何将图像保存回.png文件或任何其他图像文件格式?(我不需要alpha/透明度)


Tags: 数据django图像服务器应用程序http编码原始数据
2条回答

我很确定你需要PIL

from PIL import Image
img_size = (500, 500)
img = Image.frombytes('RGB', img_size, raw_data)
img.save('mypic.png')

剩下的都是Django的工作,对吧?在

您只需要将解码后的base64字符串中包含的字节流保存到磁盘。我只是简单地做了以下事情:

import base64

# assume 'x' is the variable where you have the base64 encoded image
# 'target.png' is the file name where you'll be saving it
# 'wb' is for a raw binary write operation
fout = open('target.png','wb')
# decode it and write it
fout.write(base64.b64decode(x))
# flush it
fout.flush()

在磁盘中写入后,只需使用文件路径将实例添加/编辑到django中的模型中。在

这对我很有用,希望对我有帮助!在

相关问题 更多 >