我正在开发一项功能,该功能允许用户将图像上传到Python-Flask Web应用程序。上传的图像将转换为BytesIO缓冲区,并且永远不会保存到磁盘。我想使用imghdr.what()
确定图像类型(png,jpg等),并查看它是否是允许用户上传的格式。如果不允许该格式,则上传将被拒绝。
在imghdr.what() documentation之后,我编写了以下代码
image_data.seek(0)
image_type = imghdr.what(None, h=image_data.read())
image_data.seek(0)
不幸的是,当我用png图片称呼它时,它为None
返回了image_type
。我用相同的图像尝试了以下变体。
image_data.seek(0)
image_type = imghdr.what('', h=image_data.read())
image_data.seek(0)
同样,以上返回None
的{{1}}。
image_type
以上内容返回错误 image_data.seek(0)
image_type = imghdr.what(None, h=image_data)
image_data.seek(0)
TypeError: '_io.BytesIO' object is not subscriptable
上面的代码返回相同的错误 image_data.seek(0)
image_type = imghdr.what('', h=image_data.read)
image_data.seek(0)
这是TypeError: '_io.BytesIO' object is not subscriptable
中创建模拟png图像的代码
conftest.py
我已经看过这些资源:
Examples of how to use imghdr.what()
Determine the type of an image in Python using imghdr
Determing the type of an image using Python imghdr
TLDR :如何让@pytest.fixture
def test_image_BytesIO():
test_dir = os.path.dirname(os.path.realpath(__file__))
local_path = os.path.join(test_dir, 'images/204Cat.png')
img_bytes = Pimage.open(local_path).tobytes()
return BytesIO(img_bytes)
处理BytesIO格式的图像?