检测文件是否是Python中的图像 [英] Detecting if a file is an image in Python

查看:661
本文介绍了检测文件是否是Python中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there any general way to detect if a file is a image (jpg, bmp, png, etc...)

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

Or is making a list of the file extensions and doing a one-by-one comparison the only way?

推荐答案

假设:

>>> files = {"a_movie.mkv", "an_image.png", "a_movie_without_extension", "an_image_without_extension"}

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

And they are proper movie and image files in script folder.

您可以使用内置mimetypes模块,但如果没有扩展名它将无法使用。

You can use builtin mimetypes module, but it won't work without extensions.

>>> 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)}

或致电unix命令 file 。这适用于没有扩展名,但不适用于Windows:

Or call the unix command file. This works without extensions, but not in 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;'}

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

Or you try to open it with PIL, and check for errors, but needs PIL installed:

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

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

Or, for simplicity, as you say, just check extensions, it's the best way I think.

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

这篇关于检测文件是否是Python中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆