使用LibJpeg图像解码

来源:互联网 发布:手机登录装修淘宝店 编辑:程序博客网 时间:2024/05/18 07:31

1 简介

libjpeg一个图片解码库,在项目中需要读入图片,但不想依赖opencv的接口,这时可以libjpeg完成解码。libjpeg有两个版本,一个时原装的libjpeg,另一个则是libjpeg-turbo,这是一个使用 SIMD指令加速的解码库,大约是libjpeg的3倍的速度,代码参见 https://github.com/libjpeg-turbo/libjpeg-turbo

2 编译

  • 下载源代码,cmake,nasm 参考(https://github.com/libjpeg-turbo/libjpeg-turbo/blob/master/BUILDING.md)

3代码

struct JPEGINFO {    unsigned int width;    unsigned int height;    ColorType colortype;    unsigned char* dstImg;};/**  输入图片名,输出unsigned char*图片数据**/int readjpeg(std::string file_name,    JPEGINFO &jpeginfo){    struct jpeg_decompress_struct cinfo;    struct my_error_mgr jerr;    FILE * infile;    JSAMPARRAY buffer;    int row_stride;    errno_t err;    if ((err = fopen_s(&infile, file_name.c_str(), "rb")) != 0)    {        fprintf(stderr, "can't open %s\n", file_name);        return -1;    }    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 -1;    }    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;    int cols = cinfo.output_width;    int rows = cinfo.output_height;    buffer = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, row_stride, 1);    jpeginfo.width = cinfo.output_width;    jpeginfo.height = cinfo.output_height;    if (cinfo.output_components == 3)    {        jpeginfo.colortype = RGB;        jpeginfo.dstImg = new unsigned char[jpeginfo.width*jpeginfo.height * 3+1];    }//gray    else{        jpeginfo.colortype = Gray;        jpeginfo.dstImg = new unsigned char[jpeginfo.width * jpeginfo.height+1];    }    while (cinfo.output_scanline < cinfo.output_height) {        (void)jpeg_read_scanlines(&cinfo, buffer, 1);        for (size_t i = 0; i < cinfo.output_width; i++)        {            //rgb            if (jpeginfo.colortype == RGB)            {                jpeginfo.dstImg[(cinfo.output_scanline - 1)*jpeginfo.width*3 + i*3] = buffer[0][i * 3];                jpeginfo.dstImg[(cinfo.output_scanline - 1)*jpeginfo.width*3 + i*3 + 1] = buffer[0][i * 3 + 1];                jpeginfo.dstImg[(cinfo.output_scanline - 1)*jpeginfo.width *3+ i*3 + 2] = buffer[0][i * 3 + 2];            }            else if (jpeginfo.colortype == Gray)            {                jpeginfo.dstImg[(cinfo.output_scanline - 1)*jpeginfo.width + i] = buffer[0][i];            }        }    }    (void)jpeg_finish_decompress(&cinfo);    jpeg_destroy_decompress(&cinfo);    fclose(infile);    return 0;}
0 0
原创粉丝点击