Detecting if a file is an image in Python

This question already has an answer here:

  • How to check if a file is a valid image file? 7 answers

  • Assuming:

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

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

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

    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}
    

    You should use a library for this. Note that extension != file type, because you can change the extension to a .jpg file, open it with paint and paint will interpret it like a jpeg (for example). You should check How to find the mime type of a file in python?.

    链接地址: http://www.djcxy.com/p/46804.html

    上一篇: 如何通过电子邮件将Django FileField作为附件发送?

    下一篇: 在Python中检测文件是否为图像