From 7fb86a0af4c9202b11c080b802ddb68400fbc3b0 Mon Sep 17 00:00:00 2001 From: Goffi Date: Tue, 14 Apr 2020 20:29:37 +0200 Subject: [PATCH] tools (image): added a guess_type method to guess media type: media type is guessed first from filename, then if it's not enough, the file is opened to try to guess type. If it still can be determined, None is returned. --- sat/tools/image.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) 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 + +