Wednesday, February 28, 2007

example code for BMP image display!

something I tried out for 256 colour bmp, with no attempt at cleanup [It is not hard after all!]:
Algorithm is here: The .bmp file format


#include "stdafx.h"
#include "ImageDisplay.h"
#include <fstream>
#include <map>
#include <CommDlg.h>
using namespace std;

....
ifstream image(fileName);
...
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code here...
int dummy;
long dummyLong;
//read header
image.read((char*)&dummy, 2);
long size;
//read file size
image.read((char*)&size, 4);
long bitmapOffset;
image.read((char*)&dummyLong, 4);
image.read((char*)&bitmapOffset, 4);
long bitMapHeaderSize;
image.read((char*)&bitMapHeaderSize, 4);
long width;
image.read((char*)&width, 4);
long height;
image.read((char*)&height, 4);
image.read((char*)&dummy, 2);
int bitsPerPixel;
image.read((char*)&bitsPerPixel, 2);
bitsPerPixel = *((char*)&bitsPerPixel);
int test;
image.read((char*)&test, 2);
int paletteOffset;
int paletteSize;
paletteSize = 4* (1 << bitsPerPixel);
paletteOffset = bitmapOffset - paletteSize;
currentPalette = new unsigned char[paletteSize];
image.seekg(paletteOffset);
int l;
for(l = 0; l < paletteSize;++l) {
image.read((char*)&(currentPalette[l]), 1);
}
image.seekg(bitmapOffset);
for(i = 0; i < height; ++i) {
for(j = 0; j < width; ++j) {
unsigned char charVal = 0;
image.read((char*)&charVal, 1);
if(0 == charVal) {
continue;
}
int val = charVal* 4;
SetPixel(hdc, j, height-i,/*RGB(r, g, b)*/RGB(currentPalette[val+2], currentPalette[val+1], currentPalette[val]));
}
}
EndPaint(hWnd, &ps);
...

No comments: