【问题标题】:Detecting if a file is an image in Python [duplicate]检测文件是否是Python中的图像[重复]
【发布时间】:2011-10-02 04:58:13
【问题描述】:

有什么通用方法可以检测文件是否为图像(jpg、bmp、png 等...)

还是列出文件扩展名并逐一比较是唯一的方法?

【问题讨论】:

标签: python image


【解决方案1】:

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

【讨论】:

  • 这已经被提及 - 这应该是一个评论,而不是一个答案
【解决方案2】:

假设:

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

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

您可以使用内置的 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)}

或者调用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;'}

或者您尝试使用 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}

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

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

【讨论】:

  • +1 提醒其他人使用 file 或选项 2 最适合我的用例,在这种用例中,我正在爬取检索返回的不带扩展名的图像,并且需要将它们另存为.jpg/.png
  • 这也有一个简单的方法...."if 'file' in request.files:" 试试这个如果有文件然后它会返回true..
  • 我正在寻找您提供的最后一个解决方案。非常感谢。
猜你喜欢
  • 2013-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-25
  • 2013-08-15
  • 2020-12-04
  • 2015-07-15
  • 1970-01-01
相关资源
最近更新 更多