2011-07-10 53 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。 。 –