检测文件是否是Python中的图像

tim*_*nti 10 python image

是否有任何通用的方法来检测文件是否是图像(jpg,bmp,png等...)

或者是制作文件扩展名列表并以唯一的方式进行逐一比较?

utd*_*mir 26

假设:

>>> files = {"a_movie.mkv", "an_image.png", "a_movie_without_extension", "an_image_without_extension"}
Run Code Online (Sandbox Code Playgroud)

它们是脚本文件夹中的正确电影和图像文件.

您可以使用内置的mimetypes模块,但如果没有扩展,它将无法工作.

>>> import mimetypes
>>> {file: mimetypes.guess_type(file) for file in files}
{'a_movie_without_extension': (None, None), 'an_image.png': ('image/png', None), 'an_image_without_extension': (None, None), 'a_movie.mkv': (None, None)}
Run Code Online (Sandbox Code Playgroud)

或者调用unix命令file.这可以不使用扩展,但不能在Windows中使用:

>>> import subprocess
>>> def find_mime_with_file(path):
...     command = "/usr/bin/file -i {0}".format(path)
...     return subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).communicate()[0].split()[1]
... 
>>> {file: find_mime_with_file(file) for file in files}
{'a_movie_without_extension': 'application/octet-stream;', 'an_image.png': 'image/png;', 'an_image_without_extension': 'image/png;', 'a_movie.mkv': 'application/octet-stream;'}
Run Code Online (Sandbox Code Playgroud)

或者您尝试使用PIL打开它,并检查错误,但需要安装PIL:

>>> from PIL import Image
>>> def check_image_with_pil(path):
...     try:
...         Image.open(path)
...     except IOError:
...         return False
...     return True
... 
>>> {file: check_image_with_pil(file) for file in files}
{'a_movie_without_extension': False, 'an_image.png': True, 'an_image_without_extension': True, 'a_movie.mkv': False}
Run Code Online (Sandbox Code Playgroud)

或者,为简单起见,正如您所说,只需检查扩展,这是我认为最好的方式.

>>> extensions = {".jpg", ".png", ".gif"} #etc
>>> {file: any(file.endswith(ext) for ext in extensions) for file in files}
{'a_movie_without_extension': False, 'an_image.png': True, 'an_image_without_extension': False, 'a_movie.mkv': False}
Run Code Online (Sandbox Code Playgroud)


Ped*_*cía 2

您应该为此使用一个库。请注意,扩展名 != 文件类型,因为您可以将扩展名更改为 .jpg 文件,用 Paint 打开它,并且 Paint 会将其解释为 jpeg(例如)。你应该检查How to find the mime type of a file in python?

  • 这已经提到过 - 这应该是评论,而不是答案 (2认同)