imghdr --- 画像の形式を決定する

ソースコード: Lib/imghdr.py

バージョン 3.11 で非推奨、バージョン 3.13 で削除予定: The imghdr module is deprecated (see PEP 594 for details and alternatives).


imghdr モジュールはファイルやバイトストリームに含まれる画像の形式を決定します。

imghdr モジュールは次の関数を定義しています:

imghdr.what(file, h=None)

Test the image data contained in the file named file and return a string describing the image type. If h is provided, the file argument is ignored and h is assumed to contain the byte stream to test.

バージョン 3.6 で変更: path-like object を受け入れるようになりました。

以下に what() からの戻り値とともにリストするように、次の画像形式が認識されます:

Image 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

'webp'

WebP files

'exr'

OpenEXR Files

バージョン 3.5 で追加: フォーマット*exr*と*webp*が追加されました.

この変数に追加することで、あなたは imghdr が認識できるファイル形式のリストを拡張できます:

imghdr.tests

個別のテストを行う関数のリスト。それぞれの関数は二つの引数をとります: バイトストリームとオープンされたファイルのようにふるまうオブジェクト。 what() がバイトストリームとともに呼び出されたときは、ファイルのようにふるまうオブジェクトは None でしょう。

テストが成功した場合は、テスト関数は画像形式を表す文字列を返すべきです。あるいは、失敗した場合は None を返すべきです。

以下はプログラム例です:

>>> import imghdr
>>> imghdr.what('bass.gif')
'gif'