PHP function to parse BMP header


Read first: BMP file structure analysis by PHP

/**
 * @author tutorialspots.com
 * @copyright 2013
 */

function bmp_header($file, &$fh='')
{
    $bmp = "";

    //read file
    if (!file_exists($file))
        return false;
    $fh = fopen($file,"r");
    while(!feof($fh)) $bmp .= fgets($fh,filesize($file));

    $header = "vfile_type/Vfile_size/Vreserved/Vbitmap_offset";
    $header .= '/Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel' .
        '/Vcompression/Vsize_bitmap/Vhoriz_resolution' .
        '/Vvert_resolution/Vcolors_used/Vcolors_important';
    $file = unpack($header, $bmp);

    // check for bitmap WINDOWS
    if ($file['file_type'] != 19778)
        return false;
    return $file;
}

Example 1:
5-5-5 16-bit

$file = 'bmp-16-555.bmp';

var_dump(
    bmp_header($file)
); 

Result:

array(15) {
  ["file_type"]=>
  int(19778)
  ["file_size"]=>
  int(151096)
  ["reserved"]=>
  int(0)
  ["bitmap_offset"]=>
  int(54)
  ["header_size"]=>
  int(40)
  ["width"]=>
  int(319)
  ["height"]=>
  int(236)
  ["planes"]=>
  int(1)
  ["bits_per_pixel"]=>
  int(16)
  ["compression"]=>
  int(0)
  ["size_bitmap"]=>
  int(151042)
  ["horiz_resolution"]=>
  int(2834)
  ["vert_resolution"]=>
  int(2834)
  ["colors_used"]=>
  int(0)
  ["colors_important"]=>
  int(0)
}

Example 2:
5-6-5 16-bit

$file = 'bmp-16-565.bmp';

var_dump(
    bmp_header($file)
); 

Result:

array(15) {
  ["file_type"]=>
  int(19778)
  ["file_size"]=>
  int(151112)
  ["reserved"]=>
  int(0)
  ["bitmap_offset"]=>
  int(70)
  ["header_size"]=>
  int(56)
  ["width"]=>
  int(319)
  ["height"]=>
  int(236)
  ["planes"]=>
  int(1)
  ["bits_per_pixel"]=>
  int(16)
  ["compression"]=>
  int(3)
  ["size_bitmap"]=>
  int(151042)
  ["horiz_resolution"]=>
  int(2834)
  ["vert_resolution"]=>
  int(2834)
  ["colors_used"]=>
  int(0)
  ["colors_important"]=>
  int(0)
}

Example 3:
4-4-4 16-bit

$file = 'bmp-16-444.bmp';

var_dump(
    bmp_header($file)
); 

Result:

array(15) {
  ["file_type"]=>
  int(19778)
  ["file_size"]=>
  int(151112)
  ["reserved"]=>
  int(0)
  ["bitmap_offset"]=>
  int(70)
  ["header_size"]=>
  int(56)
  ["width"]=>
  int(319)
  ["height"]=>
  int(236)
  ["planes"]=>
  int(1)
  ["bits_per_pixel"]=>
  int(16)
  ["compression"]=>
  int(3)
  ["size_bitmap"]=>
  int(151042)
  ["horiz_resolution"]=>
  int(2834)
  ["vert_resolution"]=>
  int(2834)
  ["colors_used"]=>
  int(0)
  ["colors_important"]=>
  int(0)
}

1 Comment

Leave a Reply