Created
October 14, 2011 10:04
-
-
Save chernomyrdin/1286725 to your computer and use it in GitHub Desktop.
Read BMP file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl -w -- | |
use strict; | |
use warnings; | |
use IO::File; | |
my %header; | |
my %bitmap; | |
my @palette; | |
my $fh = IO::File->new("_.bmp"); | |
$fh->binmode(":bytes"); | |
unless ($fh->sysread($_, 14)) { | |
die "Error read BMP header"; | |
} | |
( $header{bfType}, $header{bfSize}, $header{bfOffset} ) = unpack("A2Lx2x2L"); | |
unless ($fh->sysread($_, 4)) { | |
die "Error read BITMAP length of BMP file"; | |
} | |
( $bitmap{biSize} ) = unpack("l"); | |
unless ($fh->sysread($_, $bitmap{biSize} - 4)) { | |
die "Error read BITMAP of BMP file"; | |
} | |
( $bitmap{biWidth}, | |
$bitmap{biHeight}, | |
$bitmap{biPlanes}, | |
$bitmap{biBitCount}, | |
$bitmap{biCompression}, | |
$bitmap{biSizeImage}, | |
$bitmap{biXPelsPerMeter}, | |
$bitmap{biYPelsPerMeter}, | |
$bitmap{biClrUsed}, | |
$bitmap{biClrImportant} | |
) = unpack("llSSLLllLL"); | |
unless ($fh->sysread($_, 4 * $bitmap{biClrUsed})) { | |
die "Error read palette of BMP file"; | |
} | |
@palette = unpack("L" x $bitmap{biClrUsed}); | |
# Read file here... | |
unless ($fh->seek( $header{bfOffset} )) { | |
die "Invalid bfOffset offset in header of BMP file"; | |
} | |
my @data; | |
my $row_bytes_length = (4 * int(($bitmap{biBitCount} * $bitmap{biWidth} + 4) / 4)) / 8; | |
for (my $row_no = $bitmap{biHeight} - 1; $row_no >= 0; $row_no--) { | |
unless ($fh->sysread($data[ $row_no ], $row_bytes_length)) { | |
die "Error reading image data"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment