2023/08/27
Base64について調べる(2)
前回の続きです。Base64について詳しく理解するために、Bitmap画像をBase64フォーマットに変換する仕組みを調べました。まず、5(pixel)×8(pixel)の「1」のBitmap画像を準備しました。この画像は拡大図で、pixel情報を判別・検証するために、要所要所に色を付けました。




赤色箇所のHeaderと青色箇所のInfoHeaderの詳細は以下の通りです。
Header 14 bytesBitsPerPixelは24なので、ColorTableはなく、バイナリエディタの緑で囲んだ部分(最後まで)は「Pixel Data」です。この時、PixelDataは3バイトで青、緑、赤の明るさ(強度)をそれぞれ表し、各行は、4バイトで割り切れるようにゼロパディングされます。このことを考慮してMapを作成すると以下の通りです。
42 4D B6 00 00 00 00 00 00 00
36 00 00 00
Signature 2 bytes 0000h 'BM'
42 4D(B M)
FileSize 4 bytes 0002h File size in bytes -> 182 byte
B6 00 00 00(00-00-00-B6:182)
reserved 4 bytes 0006h unused (=0)
00 00 00 00
DataOffset 4 bytes 000Ah Offset from beginning of file to the beginning of the bitmap data
36 00 00 00
InfoHeader 40 bytes Windows Structure: BITMAPINFOHEADER
28 00 00 00 05 00 00 00 08 00
00 00 01 00 18 00 00 00 00 00
80 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00
Size 4 bytes 000Eh Size of InfoHeader = 40
28 00 00 00 (00-00-00-28; 40) Default
Width 4 bytes 0012h Horizontal width of bitmap in pixels
05 00 00 00 (5)
Height 4 bytes 0016h Vertical height of bitmap in pixels
08 00 00 00 (8)
Planes 2 bytes 001Ah Number of Planes (=1)
01 00 (1)
Bits Per Pixel 2 bytes 001Ch Bits per Pixel used to store palette entry information. This also identifies in an indirect way the number of possible colors. Possible values are:
1 = monochrome palette. NumColors = 1
4 = 4bit palletized. NumColors = 16
8 = 8bit palletized. NumColors = 256
16 = 16bit RGB. NumColors = 65536
24 = 24bit RGB. NumColors = 16M
18 00 (00-18:24)
Compression 4 bytes 001Eh Type of Compression
0 = BI_RGB no compression
1 = BI_RLE8 8bit RLE encoding
2 = BI_RLE4 4bit RLE encoding
00 00 00 00(0)
ImageSize 4 bytes 0022h (compressed) Size of Image
It is valid to set this =0 if Compression = 0
80 00 00 00(00-00-00-80:128)
XpixelsPerM 4 bytes 0026h horizontal resolution: Pixels/meter
00 00 00 00
YpixelsPerM 4 bytes 002Ah vertical resolution: Pixels/meter
00 00 00 00
Colors Used 4 bytes 002Eh Number of actually used colors. For a 8-bit / pixel bitmap this will be 100h or 256.
00 00 00 00
Important Colors 4 bytes 0032h Number of important colors 0 = all
00 00 00 00

最後に、本題のbmp画像からBase64フォーマットへの変換についてです。この5(pixel)×8(pixel)の「1」のBitmap画像をネット上でBase64フォーマットに変換すると、こんな感じでした。
Qk22AAAAAAAAADYAAAAoAAAABQAAAAgAAAABABgAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAA////////////////////AP///8xIPwAAAADy/////wD///////8AAAD///////8A////////AAAA////////AP///////wAAAP///////wD///////8AAAD///////8A////TLEiAAAA////////AP///////yQc7f///////wA=ここで、Base64の文字テーブル表を用います。

Bitmap規則に従って正しく変換されていることが分かりました。
4 2 4 D B 6 0 0
0100 0010 0100 1101 1011 0110 0000 0000
(4bitの塊を6bitの塊に変換)
010000 100100 110110 110110 000000 00
(Base64の対応表と照合)
Q k 2 2 A
今回、Base64フォーマットについて、Bitmap画像を用いて詳細に調べました。そもそものきっかけは、生成AIへの質問の結果をBase64フォーマットを用いた画像出力でできるか否かということでした。結論から言うと、前回もお話しした通り、現時点で生成AIから求めている正しい画像を得るのは難しいと判断しました。技術の進歩も速いので、いずれ正しい画像が出力できるようになるかもしれませんが・・。