首页 > 解决方案 > 将 PIL.Image 发送到 django 服务器端并取回

问题描述

我不知道将图像从客户端发送到服务器端的原理是什么,所以被下面的场景卡住了。

我想使用Python 请求库PIL.Image将对象发送到 django 服务器端 并将其取回,以便在服务器端使用该对象。正如我所测试的,如果发送的对象没有任何转换,那就是PIL.ImagePIL.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()无济于事。

标签: pythondjangopython-3.xpython-imaging-library

解决方案


用于发送图像

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'])


推荐阅读