void savePicAsHeightMap( std::string const& infile, std::string const& outfile ) { ImageIO::init(); BitMap* in = ImageIO::load( infile ); BitMap* out = new BitMap( in->getWidth(), in->getHeight() ); for( int j=0; j<in->getHeight(); j++ ) { for( int i=0; i<in->getWidth(); i++ ) { unsigned int col = in->get( i, j ); int r = ( col >> 16 ) & 0xff; int g = ( col >> 8 ) & 0xff; int b = col & 0xff; int v = (int)( (double)r * 0.2125 + (double)g * 0.7154 + (double)b * 0.0721 ) & 0xff; out->set( i, j, ( 0xff << 24 ) | ( v << 16 ) | ( v << 8 ) | v ); } } ImageIO::save( outfile, *out ); delete out; delete in; }
BitMap* BMP::load( std::string const& filename ) { FILE* f = fopen( filename.c_str(), "rb" ); assert( f ); // bitmap file header unsigned short bfType; unsigned int bfSize; unsigned short bfReserved1; unsigned short bfReserved2; unsigned int bfOffbits; fread( &bfType, 2, 1, f ); fread( &bfSize, 4, 1, f ); fread( &bfReserved1, 2, 1, f ); fread( &bfReserved2, 2, 1, f ); fread( &bfOffbits, 4, 1, f ); // bitmap info header unsigned int biSize; int biWidth; int biHeight; unsigned short biPlanes; unsigned short biBitCount; unsigned int biCompression; unsigned int biSizeImage; int biXPelsPerMeter; int biYPelsPerMeter; unsigned int biClrUsed; unsigned int biClrImportant; fread( &biSize, 4, 1, f ); fread( &biWidth, 4, 1, f ); fread( &biHeight, 4, 1, f ); fread( &biPlanes, 2, 1, f ); fread( &biBitCount, 2, 1, f ); fread( &biCompression, 4, 1, f ); fread( &biSizeImage, 4, 1, f ); fread( &biXPelsPerMeter, 4, 1, f ); fread( &biYPelsPerMeter, 4, 1, f ); fread( &biClrUsed, 4, 1, f ); fread( &biClrImportant, 4, 1, f ); BitMap* m = new BitMap( biWidth, biHeight ); // read data for( int j=0; j<biHeight; j++ ) { for( int i=0; i<biWidth; i++ ) { unsigned char a, r, g, b; fread( &b, 1, 1, f ); fread( &g, 1, 1, f ); fread( &r, 1, 1, f ); if( biBitCount == 32 ) fread( &a, 1, 1, f ); else if( biBitCount == 24 ) a = 0xff; m->set( i, biHeight - j - 1, ( a << 24 ) | ( b << 16 ) | ( g << 8 ) | r ); } } fclose( f ); return m; }