How to guess image mime type?

后端 未结 3 701
感动是毒
感动是毒 2020-12-11 06:41

How can I guess an image\'s mime type, in a cross-platform manner, and without any external libraries?

相关标签:
3条回答
  • 2020-12-11 07:16

    I've checked the popular image types' format on wikipedia, and tried to make a signature:

    def guess_image_mime_type(f):
        '''
        Function guesses an image mime type.
        Supported filetypes are JPG, BMP, PNG.
        '''
        with open(f, 'rb') as f:
            data = f.read(11)
        if data[:4] == '\xff\xd8\xff\xe0' and data[6:] == 'JFIF\0':
            return 'image/jpeg'
        elif data[1:4] == "PNG":
            return 'image/png'
        elif data[:2] == "BM":
            return 'image/x-ms-bmp'
        else:
            return 'image/unknown-type'
    
    0 讨论(0)
  • 2020-12-11 07:22

    If you can rely on the file extension you can use the mimetypes.guess_type function. Note that you may get different results on different platforms, but I would still call it cross-platform.

    0 讨论(0)
  • 2020-12-11 07:33

    If you know in advance that you only need to handle a limited number of file formats you can use the imghdr.what function.

    0 讨论(0)
提交回复
热议问题