Python development _imghdr_ image format support

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

In Python, the imghdr module provides support for image format

This module is mainly processing recognition image format

The imghdr module provides the following functions:

1 imghdr.what(filename, h=None) 
2        Tests the image data contained in the file named by filename, and returns a string describing the image type. If optional h is provided, t         he filename is ignored and h is assumed to contain the byte stream to test.
1 imghdr.tests 
2       A list of functions performing the individual tests. Each function takes two arguments: the byte-stream and an open file-like object. When         what() is called with a byte-stream, the file-like object will be None.
4       The test function should return a string describing the image type if the test succeeded, or None if it failed.

The following image format can be identified:

ValueImage format
'rgb' SGI ImgLib Files
'gif' GIF 87a and 89a Files
'pbm' Portable Bitmap Files
'pgm' Portable Graymap Files
'ppm' Portable Pixmap Files
'tiff' TIFF Files
'rast' Sun Raster Files
'xbm' X Bitmap Files
'jpeg' JPEG data in JFIF or Exif formats
'bmp' BMP files
'png' Portable Network Graphics


The following is my demo:


 1 #python imghdr
 3 #Author   :   Hongten
 4 #Mailto   :   
 5 #Blog     :    
 6 #QQ       :   648719819
 7 #Version  :   1.0
 8 #Create   :   2013-09-09
10 import os
11 import imghdr
13 #global var
14 #image path
15 IMG_PATH = None
17 __author__ = ['Hongten']
19 def get_ext(path):
20     '''return a string describing the image type.'''
21     if os.path.exists(path):
22         return imghdr.what(path)
23     else:
24         print('the path [{}] dose not exit!'.format(path))
26 def init():
27     global IMG_PATH
28     IMG_PATH = 'C:\\test\\hongten.jpg'
30 def main():
31     init()
32     img_ext = get_ext(IMG_PATH)
33     print('the image : [{}],and the type is :[{}]'.format(IMG_PATH, img_ext))
35 if __name__ == '__main__':
36     main()

Effect of operation:

the image : [C:\test\hongten.jpg],and the type is :[jpeg]

More reference

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Upton at November 16, 2013 - 7:27 PM