diff --git a/sat/tools/image.py b/sat/tools/image.py index 32828697..00f48815 100644 --- a/sat/tools/image.py +++ b/sat/tools/image.py @@ -19,6 +19,7 @@ """Methods to manipulate images""" import tempfile +import mimetypes from PIL import Image from pathlib import Path from twisted.internet import threads @@ -85,3 +86,28 @@ def resize(image_path, new_size, dest=None): The image at this path should be deleted after use """ return threads.deferToThread(_resizeBlocking, image_path, new_size, dest) + + +def guess_type(source): + """Guess image media type + + @param source(str, Path, file): image to guess type + @return (str, None): media type, or None if we can't guess + """ + if isinstance(source, str): + source = Path(source) + + if isinstance(source, Path): + # we first try to guess from file name + media_type = mimetypes.guess_type(source, strict=False)[0] + if media_type is not None: + return media_type + + # file name is not enough, we try to open it + img = Image.open(source) + try: + return Image.MIME[img.format] + except KeyError: + return None + +