码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-12-31 14:46:43      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:print   style   tde   head   bytes   pre   art   初始化   oid   

安装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\n",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<<"width:"<<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\n",&imgdata);
    if(imgdata!=NULL)
    {
        free(imgdata);
    }
    return 0;
}

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

标签:print   style   tde   head   bytes   pre   art   初始化   oid   

原文地址:https://www.cnblogs.com/feihu-h/p/12123990.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!