使用jpeg库读取jpg文件

来源:互联网 发布:淘宝时间倒计时代码 编辑:程序博客网 时间:2024/04/30 21:39

     今天使用jpeg库读取jpg文件, 编译过程中遇到了不少错误.

     开始时运行到 jpeg_create_decompress(&cinfo) 函数执行不成功. 这个问题使用其他的 jpeg.lib解决了, 但接下来是

    (void) jpeg_read_header(&cinfo, TRUE); 函数访问内存错误.这个问题一直解决不了.后来直接在别人一个已经使用jpeg库读jpg文件的程序上进行修改, 读取部分的代码还是一样,但却能运行了. 这应该是程序设置的问题. 但对比两个程序的设置,现在还是找不到区别,这留以后研究. 把代码贴出来如下:

struct my_error_mgr {
 struct jpeg_error_mgr pub; /* "public" fields */

 jmp_buf setjmp_buffer; /* for return to caller */
};

typedef struct my_error_mgr * my_error_ptr;

 


METHODDEF(void)
my_error_exit (j_common_ptr cinfo)
{
 /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
 my_error_ptr myerr = (my_error_ptr) cinfo->err;

 /* Always display the message. */
 /* We could postpone this until after returning, if we chose. */
 (*cinfo->err->output_message) (cinfo);

 /* Return control to the setjmp point */
 longjmp(myerr->setjmp_buffer, 1);
}

 

bool Image::load(const char *filename)
{
   std::string file(filename);
   if (file.substr(file.length() - 3, file.length()) != "jpg")
    return 0;

 

  struct jpeg_decompress_struct cinfo;
  struct my_error_mgr jerr;
  FILE * infile;  
  JSAMPARRAY buffer; 
  int row_stride;  

  if ((infile = fopen(file.c_str(), "rb")) == NULL) {
    fprintf(stderr, "can't open %s/n", file.c_str());
    return 0;
  }

  cinfo.err = jpeg_std_error(&jerr.pub);
  jerr.pub.error_exit = my_error_exit;

  
  if (setjmp(jerr.setjmp_buffer)) {
    jpeg_destroy_decompress(&cinfo);
    fclose(infile);
    return 0;
  }

  jpeg_create_decompress(&cinfo);
  jpeg_stdio_src(&cinfo, infile);
  (void) jpeg_read_header(&cinfo, TRUE);
  (void) jpeg_start_decompress(&cinfo);


  row_stride = cinfo.output_width * cinfo.output_components;
  const int component = cinfo.output_components;

  buffer = (*cinfo.mem->alloc_sarray)
    ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);

  w = cinfo.output_width;
  h = cinfo.output_height;

  create(w,h);
  int y=0;
  while (cinfo.output_scanline < cinfo.output_height) {
    (void) jpeg_read_scanlines(&cinfo, buffer, 1);


  if (component==3)
  {
    for (int i = 0; i < w; ++i)
        set_pixel(i,h-y-1,(unsigned char)buffer[3*i+0],(unsigned char)buffer[3*i+1],(unsigned char)buffer[3*i+2]);
  }else if (component==1)
  {
       for (int i = 0; i < w; ++i)
        set_pixel(i,h-y-1,(unsigned char)buffer[3*i],(unsigned char)buffer[3*i],(unsigned char)buffer[3*i]);
  }

  y++;
  }
  (void) jpeg_finish_decompress(&cinfo);
  jpeg_destroy_decompress(&cinfo);
  fclose(infile);

  return 1;
}