From 2cb77c470214457bcd85392b0e3d6003fea150b3 Mon Sep 17 00:00:00 2001 From: Dave T <17680170+davet2001@users.noreply.github.com> Date: Thu, 31 Mar 2022 23:05:39 +0100 Subject: [PATCH] Improve image checks for generic camera (#69037) --- homeassistant/components/generic/config_flow.py | 12 +++++++++--- homeassistant/components/generic/manifest.json | 2 +- requirements_all.txt | 1 + requirements_test_all.txt | 1 + 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/generic/config_flow.py b/homeassistant/components/generic/config_flow.py index c5c645264d6..d3b2a260477 100644 --- a/homeassistant/components/generic/config_flow.py +++ b/homeassistant/components/generic/config_flow.py @@ -4,12 +4,13 @@ from __future__ import annotations import contextlib from errno import EHOSTUNREACH, EIO from functools import partial -import imghdr +import io import logging from types import MappingProxyType from typing import Any from urllib.parse import urlparse, urlunparse +import PIL from async_timeout import timeout import av from httpx import HTTPStatusError, RequestError, TimeoutException @@ -110,9 +111,14 @@ def build_schema( def get_image_type(image): """Get the format of downloaded bytes that could be an image.""" - fmt = imghdr.what(None, h=image) + fmt = None + imagefile = io.BytesIO(image) + with contextlib.suppress(PIL.UnidentifiedImageError): + img = PIL.Image.open(imagefile) + fmt = img.format.lower() + if fmt is None: - # if imghdr can't figure it out, could be svg. + # if PIL can't figure it out, could be svg. with contextlib.suppress(UnicodeDecodeError): if image.decode("utf-8").lstrip().startswith("