自上周以来,我一直在尝试在屏幕上加载和显示 PNG。我使用库 libpng 将 png 复制到内存中,然后使用 glDrawPixels 在屏幕上显示它。结果如下:
原图:
“游戏”中的截图:
而代码,我正在使用静态 Image::loadPNG 将 PNG 加载到地图中,如下所示:
bool Image::loadPNG( std::string _image, FILE * file, unsigned char header[ 54 ] )
{
fseek( file, 8, SEEK_SET );
ImageData* imageData = new ImageData( );
Image* image = new Image( );
image->type = IMAGETYPE_PNG;
imageData->image = image;
png_structp png_ptr = png_create_read_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL );
if( !png_ptr )
{
std::cout << "png_create_read_struct failed. " << std::endl;
return false;
}
png_infop info_ptr = png_create_info_struct(png_ptr);
if( !info_ptr )
{
std::cout << "png_create_info_struct failed. " << std::endl;
return false;
}
if( setjmp( png_jmpbuf( png_ptr ) ) )
{
std::cout << "Error during init_io. " << std::endl;
return false;
}
png_init_io( png_ptr, file );
png_set_sig_bytes( png_ptr, 8 );
png_read_info( png_ptr, info_ptr );
png_set_strip_16( png_ptr );
png_read_update_info(png_ptr, info_ptr);
int bit_depth;
int color;
png_get_IHDR(png_ptr, info_ptr, &image->width, &image->height, &bit_depth, &color, NULL, NULL, NULL);
png_read_update_info(png_ptr, info_ptr);
int pitch = png_get_rowbytes(png_ptr, info_ptr);
image->image = new unsigned char[pitch * image->height];
png_bytep* row_pointers = new png_bytep[image->height];
for (int y = 0; y < image->height; y++)
row_pointers[image->height - 1 - y] = image->image + y * pitch;
png_read_image(png_ptr, row_pointers);
delete[] row_pointers;
// tym na razie dupy sobie nie zawracam
Image::images.insert( std::pair< std::string, ImageData* >( _image, imageData ) );
glGenTextures(1, &imageData->texture);
glBindTexture( GL_TEXTURE_2D, imageData->texture );
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image->width, image->height, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, image->image);
gluBuild2DMipmaps( GL_TEXTURE_2D, 4, image->width, image->height, GL_RGBA, GL_UNSIGNED_BYTE, image->image );
return true;
}
最后在 OpenGL 中显示它:
Image* image = Image::images["f.png"]->image;
if( image )
{
glDisable(GL_DEPTH_TEST);
glPushMatrix( );
//glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
float nx = 0.0f;
float ny = 0.0f;
glLoadIdentity( );
glTranslatef( 0, 0, -1 );
if( nx > 0 || ny > 0 )
glRasterPos2f( nx, ny );
else
{
glRasterPos2f( 0, 0 );
glBitmap(0,0,0,0, nx, ny, NULL);
}
glDrawPixels( image->width, image->height, GL_RGBA, GL_UNSIGNED_BYTE, image->image);
glPopMatrix( );
glEnable(GL_DEPTH_TEST);
}
如您所见,颜色与应有的颜色不同。谁能帮我弄清楚如何解决我的问题?