2011-07-10 33 views
7

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

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

+1

根据标准的python文件类型http://docs.python.org/c-api/concrete.html图像文件不是标准的,所以我猜想会需要一些外部模块。 – timonti

+2

使用'imghdr'模块。请参阅[如何检查文件是否是有效的图像文件?](http://stackoverflow.com/questions/889333/how-to-check-if-a-file-is-a-valid-image-file) –

回答

1

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

+2

这已被提及 - 这应该是一个评论,而不是回答 –

18

假设:

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

+1注意到其他人使用'文件'或选项二最适合我的使用情况下,我爬行检索无返回的图像扩展名,并需要将它们保存为.jpg/.png – matchew

+0

还有一个简单的方法来解决这个问题....“request.files中的if file':”如果有文件,试试这个,那么它将返回true。 。 –