encode RGB24 to jpeg, using libjpeg

来源:互联网 发布:c语言编程大赛 编辑:程序博客网 时间:2024/05/20 18:19


#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);
}

原创粉丝点击