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.
This commit is contained in:
Goffi 2020-04-14 20:29:37 +02:00
commit 7fb86a0af4

View file

@ -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