我有一个可以将图像上传到我的视图的表单;上传的图片类型是:
<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
我想处理图像;因此我需要 PIL 或 CV2 格式。
我怎样才能做到这一点?
Django
File
实际上实现了 PIL.Image.open()
所需的典型文件对象所需的所有方法。 InMemoryUploadedFile
是 Django File
。
您可以在正确的
File
中重新打开mode
,然后将其传递给PIL.Image.open()
。这应该足够了:[1]
someFile: InMemoryUploadedFile = # •••Already has a value•••
someFile = someFile.open("b+")
with PIL.Image.open(someFile) as img:
# •••Do something•••
[1] 该解决方案不会复制文件对象的底层字节,而只是将其句柄从一个例程传递到另一个例程。谨防数据争用。