# HG changeset patch # User Goffi # Date 1586888977 -7200 # Node ID 54934ee3f69c73b9566a2c4c59220c8a30c38355 # Parent f21412896620a6407e468914cc7f890192ccd387 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. diff -r f21412896620 -r 54934ee3f69c sat/tools/image.py --- 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 + +