libjpeg(1)----读取图像

安装libjpeg: sudo apt-get install libjpeg-dev

demo

#include <iostream>
#include <jpeglib.h>
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>


int readJpegFromFile(const char *input_filename,unsigned char * &output_buffer)
{
    struct jpeg_decompress_struct cinfo;  //jpeg压缩结构
    struct jpeg_error_mgr jerr;
    FILE* input_file;  //输入文件
    JSAMPARRAY  buffer;
    int row_width;

    //unsigned char * output_buffer;
    unsigned char * tmp=NULL;

    cinfo.err = jpeg_std_error(&jerr);
    // 打开输入文件
    if((input_file=fopen(input_filename,"rb"))==NULL)
    {
        fprintf(stderr,"can't open %s
",input_filename);
    }

    // 初始化jpeg压缩结构
    jpeg_create_decompress(&cinfo);
    // 设置数据源文件
    jpeg_stdio_src(&cinfo,input_file);
    // 设置读取jpeg 头部
    (void) jpeg_read_header(&cinfo,TRUE);
    // 开始解码数据
    (void) jpeg_start_decompress(&cinfo);

    std::cout<<"输出一些图像的信息:"<<std::endl;
    std::cout<<""<<cinfo.image_width<<std::endl;
    std::cout<<"height:"<<cinfo.image_height<<std::endl;
    std::cout<<"色彩空间:"<<cinfo.jpeg_color_space<<std::endl;
    std::cout<<"颜色通道数:"<<cinfo.num_components<<std::endl;
    std::cout<<"总共字节数:"<<cinfo.image_width*cinfo.image_height*cinfo.output_components<<std::endl;
    int bytes = cinfo.image_width*cinfo.image_height*cinfo.output_components;

    // 行宽度
    row_width = cinfo.output_width * cinfo.output_components; // R G B R G B
    // 跳过头文件字节
    buffer = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo,JPOOL_IMAGE,row_width,1);

    output_buffer=(unsigned char*)malloc(row_width*cinfo.output_height);
    // 初始化为0
    memset(output_buffer,0,row_width*cinfo.output_height);
    tmp = output_buffer;
    // 读取数据 行扫描
    while(cinfo.output_scanline<cinfo.output_height)
    {
       (void)jpeg_read_scanlines(&cinfo,buffer,1);
       memcpy(tmp,*buffer,row_width);
       tmp+=row_width;
    }
    (void)jpeg_finish_decompress(&cinfo);
    // 关闭文件
    fclose(input_file);

    return bytes;
}
int main()
{
    std::cout << "Hello, World!" << std::endl;
    unsigned char *imgdata=NULL;
    readJpegFromFile("7.jpg",imgdata);

    printf("地址:%p
",&imgdata);
    if(imgdata!=NULL)
    {
        free(imgdata);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/feihu-h/p/12123990.html