libpng的PNG圖片讀取,該程序只支持RGBA方案的PNG圖片不支持PNG其他方案特性
#include <stdio.h>
#include <stdlib.h>
#include <GL\glew.h>
#include <GL\glut.h>
#include "png.h"
#pragma comment(lib, "glew32.lib")
int window_width=600;
int window_height=600;
int pic_width;
int pic_height;
int size;
GLuint texName;
unsigned char *content;
void init()
{
glewInit();
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGenTextures(1, &texName);
glBindTexture(GL_TEXTURE_2D, texName);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
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, pic_width, pic_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, content);
}
void display_func()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 1.0f, 0.0, 1.0f);
glViewport(0, 0, window_width, window_height);
glClearColor(1.0f, 1.0f, 1.0f, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glEnable(GL_TEXTURE_2D);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glBindTexture(GL_TEXTURE_2D, texName);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 1.0f); glVertex2f(0.0f, 0.0f);
glTexCoord2f(1.0f, 1.0f); glVertex2f(1.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f); glVertex2f(1.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex2f(0.0f, 1.0f);
glEnd();
glutSwapBuffers();
}
void reshape_func(int width, int height)
{
window_width=width;
window_height=height;
glutReshapeWindow(window_width, window_height);
}
int main(int argc, char **argv)
{
FILE* file = fopen("wiki.png", "rb");
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
png_infop info_ptr = png_create_info_struct(png_ptr);
setjmp(png_jmpbuf(png_ptr));
png_init_io(png_ptr, file);
png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_EXPAND, 0);
pic_width = png_get_image_width(png_ptr, info_ptr);
pic_height = png_get_image_height(png_ptr, info_ptr);
int color_type = png_get_color_type(png_ptr, info_ptr);
size = pic_height * pic_width * 4;
int pos = 0;
content=(unsigned char *)malloc(sizeof(unsigned char)*size);
png_bytep* row_pointers = png_get_rows(png_ptr, info_ptr);
for(int i=0; i
{
for(int j=0; j
{
content[i*pic_width*4+j*4+0]=row_pointers[i][j*4+0];
content[i*pic_width*4+j*4+1]=row_pointers[i][j*4+1];
content[i*pic_width*4+j*4+2]=row_pointers[i][j*4+2];
content[i*pic_width*4+j*4+3]=row_pointers[i][j*4+3];
}
}
png_destroy_read_struct(&png_ptr, &info_ptr, 0);
fclose(file);
window_width=pic_width;
window_height=pic_height;
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutInitWindowSize(window_width, window_height);
glutCreateWindow("Picture");
init();
glutDisplayFunc(display_func);
glutReshapeFunc(reshape_func);
glutMainLoop();
free(content);
return 0;
}
顯示結果
libpng 的詳細介紹:請點這裡
libpng 的下載地址:請點這裡