什么()不适用于BytesIO bu

2024-05-15 02:02:45 发布

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

我正在开发一个功能,允许用户将图像上传到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)

同样,上面的函数返回了Nonefor 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

这是我在conftest.py中创建模拟png图像的代码

@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)

我已经看过这些资源:
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:如何让imghdr.what()处理BytesIO格式的图像?你知道吗


Tags: pathtest图像imagenonereaddatapng

热门问题