2011-07-10 1 views
7

の画像であれば(... JPG、BMP、PNG、など)ファイルが画像であるかどうかを検出するための任意の一般的な方法はありファイルは、Python

を検出またはファイル拡張子のリストを作っています唯一の方法で1つずつ比較していますか?

+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を呼び出します。あなたのように、簡単にするために、

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

または:これは拡張子なしで動作しますが、いない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を必要としますエクステンションをチェックするだけでいいと思う。

>>> 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です。他の人には、ファイルまたはオプション2の使用が、私が使用した拡張子とどちらかを.jpg/.pngとして保存する必要があります。.jpg/.png – matchew

+0

これにも簡単な方法があります.... "request.filesの 'file'の場合:"ファイルがあればこれを試してください。 。 –