python - 将 PIL.Image 发送到 django 服务器端并取回
问题描述
我不知道将图像从客户端发送到服务器端的原理是什么,所以被下面的场景卡住了。
我想使用Python 请求库PIL.Image
将对象发送到 django 服务器端 并将其取回,以便在服务器端使用该对象。正如我所测试的,如果发送的对象没有任何转换,那就是PIL.Image
PIL.Image
r = requests.post(SERVER_URL,
data={
'image': PILimage,#PILimage is of type PIL.Image
'wordPos':(86,23)
},
)
然后我刚刚在服务器端获得了一个str
具有值的对象 <PIL.PngImagePlugin.PngImageFile image mode=RGB size=149x49 at 0x13F25D0>
,我猜它是由 引起的 requests
,它在发送之前将PIL.Image
对象转换为对象str
,那么为什么要 requests
进行转换?为什么我们不能在PIL.Image
没有任何转换的情况下通过 Internet 发送对象?请在这里给出一些解释,谢谢!
有人告诉我我可以将PIL.Image
对象转换为bytes
形式然后进行发送,即
r = requests.post(SERVER_URL,
data={
'image': PILimage.tobytes(),#PILimage is of type PIL.Image
'wordPos':(86,23)
},
)
但是然后 如何将图像返回到PIL.Image
服务器端的对象?似乎PIL.Image.frombytes()无济于事。
解决方案
用于发送图像
def myOCR(PILimage, wordPos):
image = io.BytesIO()
PILimage.save(image, 'png') # 没有什么类型,这里就任意指定个吧;For images created by the library itself (via a factory function, or by running a method on an existing image), this attribute is set to None.
image.seek(0) # 要回到开始才行,不然后面requests读的时候会从结尾读,读不到数据
r = requests.post(SERVER_URL,
files={'image': image},
data={'wordPos': wordPos}
)
result = r.json()
return result['word']
在 Django 方面,可以使用Image.open(request.FILES['image'])
推荐阅读
- javascript - 使用 php 在 ajax 中发布让我未定义的索引
- python - Tensorflow:如何使用另一个未知维度的张量来索引一个张量?
- perl - Perl 与 XML::LibXML Dom(全局查找和替换 XML)
- sql-server - SSRS 图“类别组”
- maple - 如何在特殊点绘制实验数据?
- linux - nano 中的语法突出显示不适用于特定语言
- c# - 为什么即使在 Azure 中配置了所需的设置后,我也看不到应用服务中的日志?
- android - Ubuntu - Jenkins 无法访问已安装的硬盘
- swift - 如何约束泛型函数关联类型
- html - CSS选择多个标签