近来在工作中用到libpng和libjpeg对图片做解析,要求解析出RGB数据,并能提供8位和24位2中借口,并要求能对图片进行缩放,结合网上各个朋友的文章,写出了我自己的代码,现在贴出来给大家参考。
1.从文件读取:
bool PngImage::loadFromFile(const char* Path, IMAGE_TYPE type)
{
// 重新初始化,防止load多个图片。
m_good = false;
m_width = 0;
m_height = 0;
if (m_bgra)
{
delete m_bgra;m_bgra = 0;//类成员变量,存储24位RGB数据。
}
if(m_8bit)
{
delete m_8bit;m_8bit=0;//类成员变量,存储8位数据。
}
if(type == IMAGE_PNG)
{
//对PNG文件的解析
// try to open file
FILE* file = fopen(Path, "rb");
// unable to open
if (file == 0) return false;
// create read struct
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
// check pointer
if (png_ptr == 0)
{
fclose(file);
return false;
}
// create info struct
png_infop info_ptr = png_create_info_struct(png_ptr);
// check pointer
if (info_ptr == 0)
{
png_destroy_read_struct(&png_ptr, 0, 0);
fclose(file);
return false;
}
// set error handling
if (setjmp(png_jmpbuf(png_ptr)))
{
png_destroy_read_struct(&png_ptr, &info_ptr, 0);
fclose(file);
return false;
}
// I/O initialization using standard C streams
png_init_io(png_ptr, file);
// read entire image , ignore alpha channel,如果你要使用alpha通道,请把PNG_TRANSFORM_STRIP_ALPHA去掉
png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_EXPAND | PNG_TRANSFORM_STRIP_ALPHA, 0);
/*
PNG_TRANSFORM_EXPAND有下边几个处理:
1.Expand paletted colors into true RGB triplets
2.Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
3.Expand paletted or RGB images with transparency to full alpha channels so the data will be available
as RGBA quartets。
PNG_TRANSFORM_STRIP_ALPHA:Strip alpha bytes from the input data without combining withthe background
*/
int width = m_width = info_ptr->width;