I am working on a feature that allows users to upload images to a Python-Flask web app. The uploaded image is converted into a BytesIO buffer and is never saved to disk. I want to use imghdr.what()
to determine the image type (png, jpg, etc.) and see if it is a format that users are allowed to upload. If the format is not allowed, the upload will be rejected.
Following the imghdr.what() documentation, I wrote the below code,
image_data.seek(0)
image_type = imghdr.what(None, h=image_data.read())
image_data.seek(0)
Unfortunately,when I call this with a png image, it returns None
for image_type
. I tried the below variations with the same image.
image_data.seek(0)
image_type = imghdr.what('', h=image_data.read())
image_data.seek(0)
Again, the above returned None
for image_type
.
image_data.seek(0)
image_type = imghdr.what(None, h=image_data)
image_data.seek(0)
The above returns an error, TypeError: '_io.BytesIO' object is not subscriptable
image_data.seek(0)
image_type = imghdr.what('', h=image_data.read)
image_data.seek(0)
The above returns the same error, TypeError: '_io.BytesIO' object is not subscriptable
Here is the code from conftest.py
where I create the mock png image,
@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)
I've already looked at these resources:
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: How do I get imghdr.what()
to work with an image that is in BytesIO format?