使用libjpeg进行图片读取

1 简介

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

2 编译

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;

}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值