encode RGB24 to jpeg, using libjpeg

这段代码展示了如何使用libjpeg库将RGB24格式的图像数据编码并保存为JPEG文件。它定义了一个名为`encode_jpeg_file`的函数,接受图像文件名和质量参数,通过设置JPEG压缩结构、打开文件、设置图像属性、设置质量、开始压缩、写入扫描线并完成压缩来实现这一过程。

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


#include <stdio.h>
#include "jpeglib.h"
#include <setjmp.h>

extern JSAMPLE * image_buffer;    /* Points to large array of R,G,B-order data */
extern int image_height;    /* Number of rows in image */
extern int image_width;        /* Number of columns in image */

void encode_jpeg_file (char * filename, int quality)
{
  struct jpeg_compress_struct cinfo;
  struct jpeg_error_mgr jerr;
  FILE * outfile;        /* target file */
  JSAMPROW row_pointer[1];    /* pointer to JSAMPLE row[s] */
  int row_stride;        /* physical row width in image buffer */
  cinfo.err = jpeg_std_error(&jerr);
  jpeg_create_compress(&cinfo);

  if ((outfile = fopen(filename, "wb")) == NULL) {
    fprintf(stderr, "can't open %s/n", filename);
    exit(1);
  }
  jpeg_stdio_dest(&cinfo, outfile);
 
  cinfo.image_width = image_width;     
  cinfo.image_height = image_height;
  cinfo.input_components = 3;        
  cinfo.in_color_space = JCS_RGB;     
 
  jpeg_set_defaults(&cinfo);
 
  jpeg_set_quality(&cinfo, quality, TRUE );

  jpeg_start_compress(&cinfo, TRUE);
 
  row_stride = image_width * 3;    

  while (cinfo.next_scanline < cinfo.image_height)
  {
    /* jpeg_write_scanlines expects an array of pointers to scanlines.
     * Here the array is only one element long, but you could pass
     * more than one scanline at a time if that's more convenient.
     */
    row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
    (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
  }
  jpeg_finish_compress(&cinfo);
  fclose(outfile);
  jpeg_destroy_compress(&cinfo);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值