imghdr

How to check if a file is a valid image file?

半腔热情 提交于 2020-01-26 10:39:53
问题 I am currently using PIL. from PIL import Image try: im=Image.open(filename) # do stuff except IOError: # filename not an image file However, while this sufficiently covers most cases, some image files like, xcf, svg and psd are not being detected. Psd files throws an OverflowError exception. Is there someway I could include them as well? 回答1: A lot of times the first couple chars will be a magic number for various file formats. You could check for this in addition to your exception checking

Django content type of an image file

泪湿孤枕 提交于 2019-12-11 03:43:45
问题 I want to check a file type before uploading it by: content = self.cleaned_data['picture'] content_type = content.content_type.split('/')[0] When I upload the picture I get an error: 'NoneType' object has no attribute 'content_type' What can be wrong here? 回答1: imghdr.what will return image format as string (gif, png etc.) if the image is valid, or None otherwise. Usage: import imghdr imghdr.what(value) In the above example value can be either a file(-like) object or a filename. 来源: https:/

How to check if a file is a valid image file?

核能气质少年 提交于 2019-11-26 18:39:53
I am currently using PIL. from PIL import Image try: im=Image.open(filename) # do stuff except IOError: # filename not an image file However, while this sufficiently covers most cases, some image files like, xcf, svg and psd are not being detected. Psd files throws an OverflowError exception. Is there someway I could include them as well? A lot of times the first couple chars will be a magic number for various file formats. You could check for this in addition to your exception checking above. I have just found the builtin imghdr module. From python documentation: The imghdr module determines