使用libpng,libjpeg从文件读取和从内存读取2中方式的实现

这篇博客分享了如何使用libpng和libjpeg库解析图片,包括从文件读取PNG和JPEG图片,获取RGB数据,并提供了8位和24位接口。代码实现了从文件加载图片并进行缩放的功能,详细展示了libpng和libjpeg的读取流程及内存读取的回调函数设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     近来在工作中用到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;
 

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值