changeset 3252:54934ee3f69c

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.
author Goffi <goffi@goffi.org>
date Tue, 14 Apr 2020 20:29:37 +0200
parents f21412896620
children 1af840e84af7
files sat/tools/image.py
diffstat 1 files changed, 26 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/sat/tools/image.py	Tue Apr 14 20:26:47 2020 +0200
+++ b/sat/tools/image.py	Tue Apr 14 20:29:37 2020 +0200
@@ -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 @@
         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
+
+