How to guess image mime type?

≡放荡痞女 提交于 2019-11-27 19:24:19

问题


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


回答1:


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




回答2:


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'



回答3:


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.



来源:https://stackoverflow.com/questions/14644880/how-to-guess-image-mime-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!