comparison sat/tools/image.py @ 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 4fbea7f1e012
children f300d78f08f3
comparison
equal deleted inserted replaced
3251:f21412896620 3252:54934ee3f69c
17 # along with this program. If not, see <http://www.gnu.org/licenses/>. 17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 18
19 """Methods to manipulate images""" 19 """Methods to manipulate images"""
20 20
21 import tempfile 21 import tempfile
22 import mimetypes
22 from PIL import Image 23 from PIL import Image
23 from pathlib import Path 24 from pathlib import Path
24 from twisted.internet import threads 25 from twisted.internet import threads
25 26
26 27
83 - file: a file object which must be opened for writing in binary mode 84 - file: a file object which must be opened for writing in binary mode
84 @return (Path): path of the resized file. 85 @return (Path): path of the resized file.
85 The image at this path should be deleted after use 86 The image at this path should be deleted after use
86 """ 87 """
87 return threads.deferToThread(_resizeBlocking, image_path, new_size, dest) 88 return threads.deferToThread(_resizeBlocking, image_path, new_size, dest)
89
90
91 def guess_type(source):
92 """Guess image media type
93
94 @param source(str, Path, file): image to guess type
95 @return (str, None): media type, or None if we can't guess
96 """
97 if isinstance(source, str):
98 source = Path(source)
99
100 if isinstance(source, Path):
101 # we first try to guess from file name
102 media_type = mimetypes.guess_type(source, strict=False)[0]
103 if media_type is not None:
104 return media_type
105
106 # file name is not enough, we try to open it
107 img = Image.open(source)
108 try:
109 return Image.MIME[img.format]
110 except KeyError:
111 return None
112
113