Skip to content

Instantly share code, notes, and snippets.

@maple-nishiyama
Created December 19, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maple-nishiyama/d27e362bff5766862908 to your computer and use it in GitHub Desktop.
Save maple-nishiyama/d27e362bff5766862908 to your computer and use it in GitHub Desktop.
Bitmap ファイルを読んでみる
<?php
// ファイルを開く
$fp = fopen('./logo_blog.bmp', 'r');
// ファイルヘッダの解析
$fielHeaderFormat = [
'a2'.'bfType',
'V'. 'bfSize',
'v2'.'bfReserved',
'V'. 'bfOffBits',
];
// ファイルの先頭14バイトを読む
$rawFileHeader = fread($fp, 14);
$fileHeader = unpack(implode('/', $fielHeaderFormat), $rawFileHeader);
print_r($fileHeader);
// 情報ヘッダの解析
// まず情報ヘッダの長さを読む
$rawBcSize = fread($fp, 4);
$bcSize = unpack('VbcSize', $rawBcSize);
print_r($bcSize);
// 情報ヘッダの残りの部分を読む
$infoHeaderFormat = [
'V'.'biWidth',
'V'.'biHeight',
'v'.'biPlanes',
'v'.'biBitCount',
'V'.'biSizeImage',
'V'.'biXPixPerMeter',
'V'.'biYPixPerMeter',
'V'.'biClrUsed',
'V'.'biCirImportant',
];
$rawInfoHeader = fread($fp, $bcSize['bcSize'] - 4);
$infoHeader = unpack(implode('/', $infoHeaderFormat), $rawInfoHeader);
print_r($infoHeader);
// 画像データ部分のサイズ
$dataSize = $fileHeader['bfSize'] - $bcSize['bcSize'];
// 縦横ピクセル数
$width = $infoHeader['biWidth'];
$height = $infoHeader['biHeight'];
// 横は4バイトの倍数に揃えなければならないのでパディングが必要か?
$res = ($width * 3) % 4;
$padding = $res > 0 ? 4 - $res : 0;
// 変換後のビットマップファイル用のヘッダとピクセルデータ用の領域
$newBitmapHeader = $rawFileHeader . $rawBcSize . $rawInfoHeader;
$newBitmapData = array_fill(0, $dataSize, 0);
// ピクセルのデータを取り出す
for ($y = 0; $y < $height; $y++) {
for ($x = 0; $x < $width; $x++) {
// 3バイト ( = 24bit) ずつ読み込む
$pixel = fread($fp, 3);
list($r, $g, $b) = array_merge(unpack('C3', $pixel));
$i = (int)(($r + $g + $b) / 3);
$newBitmapData[$ind++] = pack('C', $i);
$newBitmapData[$ind++] = pack('C', $i);
$newBitmapData[$ind++] = pack('C', $i);
}
// パディングの処理
for ($p = 0; $p < $padding; $p++) {
fread($fp, 1); // 読み捨て
$newBitmapData[$ind++] = pack('C', 0);
}
}
$newBitmap = $newBitmapHeader . implode('', $newBitmapData);
file_put_contents('./new_log_blog.bmp', $newBitmap);
fclose($fp);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment