LoginSignup
2
2

More than 3 years have passed since last update.

PythonでBMPファイルを読み込む

Last updated at Posted at 2021-02-05

対象

いわゆる256bmpが対象です。
外部ライブラリは使っていません。
python3.9で動作確認しましたが、多少下のバージョンでも動くかもしれません。
対象読者は、どちらかというと、256bmpのフォーマットを知っており、他の言語で256bmpの読み書きを実装したことがある人です。
すぐ使えること、行数が少ないこと、ある程度読みやすいことを優先しています。堅牢さや多機能さの優先度は下げています。

経緯

256bmpのフォーマットはシンプルで、多少の加工であれば、幅、高さ、パレット、画素の4つがあれば十分です。
ならば小物ツールを作るとき、install不要の標準ライブラリだけで楽に実装できそうです。

ということで参考情報を探すべく「python BMP 読み書き」等でぐぐったのですが、ドンピシャのものが見つからなかったため作りました。

なお、用途によっては画像系の外部ライブラリを使うことも多いでしょうし、あくまで参考になれば程度です。

サンプルコード

bmpRead.py
#!/usr/bin/env python3.9
"""
BMP to bytes
用途
  BMPファイルからパレットと画像を得る
使用方法
  readBmp() を呼び出す
"""

def read256BmpFile(filename):
  with open(filename, 'rb') as f:
    # いわゆる '256bmp' 専用。それ以外での動作は未定義。

    # BMP file header
    f.read(2) #bfType         = f.read(2) # 今後エラーチェック追加時に利用したいときなど用。以降の類似したコメントアウトも同様
    f.read(4) #bfSize         = int.from_bytes(f.read(4), byteorder='little')
    f.read(2) #bfReserved1    = int.from_bytes(f.read(2), byteorder='little')
    f.read(2) #bfReserved2    = int.from_bytes(f.read(2), byteorder='little')
    f.read(4) #bfOffBits      = int.from_bytes(f.read(4), byteorder='little')

    # BMP information header
    f.read(4) #bcSize         = int.from_bytes(f.read(4), byteorder='little')
    bcWidth                   = int.from_bytes(f.read(4), byteorder='little')
    bcHeight                  = int.from_bytes(f.read(4), byteorder='little')
    f.read(2) #bcPlanes       = int.from_bytes(f.read(2), byteorder='little')
    f.read(2) #bcBitCount     = int.from_bytes(f.read(2), byteorder='little')
    f.read(4) #biCompression  = int.from_bytes(f.read(4), byteorder='little')
    f.read(4) #biSizeImage    = int.from_bytes(f.read(4), byteorder='little')
    f.read(4) #biXPixPerMeter = int.from_bytes(f.read(4), byteorder='little')
    f.read(4) #biYPixPerMeter = int.from_bytes(f.read(4), byteorder='little')
    biClrUsed                 = int.from_bytes(f.read(4), byteorder='little')
    f.read(4) #biCirImportant = int.from_bytes(f.read(4), byteorder='little')

    if not biClrUsed:
        biClrUsed = 256

    # color table
    colorTable = f.read(biClrUsed * 4)

    # pixels
    pixels = f.read()

    return (bcWidth, bcHeight, colorTable, pixels)

(width, height, colorTable, pixels) = read256BmpFile('sample.bmp')

print(width, height, colorTable, pixels)

サンプルコードの使用方法

PythonでBMPファイルを出力する
を実行後に使用すると、生成された sample.bmp を読み込んで内容をprintします。

参考

PythonでBMPファイルを出力する

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2