使用libjpeg进行JPEG图像解码



如题:如何对test.jpg进行解码?


注:这里使用libjpeg库进行图像解码。也可以不使用libjpeg库,但是比较繁琐。


直接上代码:

#include "jpeglib.h"

#include <stdio.h>

#include <stdlib.h>

#include <string.h>


int main()

{

FILE *input_file;

input_file=fopen("test.jpg","rb");
 

struct jpeg_decompress_struct cinfo;//JPEG图像在解码过程中,使用jpeg_decompress_struct类型的结构体来表示,图像的所有信息都存储在结构体中
    struct jpeg_error_mgr jerr;//定义一个标准的错误结构体,一旦程序出现错误就会调用exit()函数退出进程

   

cinfo.err = jpeg_std_error(&jerr);//绑定错误处理结构对象

    jpeg_create_decompress(&cinfo);//初始化cinfo结构
    jpeg_stdio_src(&cinfo,input_file);//指定解压缩数据源
    jpeg_read_header(&cinfo,TRUE);//获取文件信息
    jpeg_start_decompress(&cinfo);//开始解压缩

    unsigned long width = cinfo.output_width;//图像宽度
    unsigned long height = cinfo.output_height;//图像高度
    unsigned short depth = cinfo.output_components;//图像深度

     unsigned char *src_buff;//用于存取解码之后的位图数据(RGB格式)
src_buff = (unsigned char *)malloc(width * height * depth);//分配位图数据空间
    memset(src_buff, 0, sizeof(unsigned char) * width * height * depth);//清0

     JSAMPARRAY buffer;//用于存取一行数据
    buffer = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, width*depth, 1);//分配一行数据空间

unsigned char *point = src_buff;
    while(cinfo.output_scanline < height)//逐行读取位图数据
    {
        jpeg_read_scanlines(&cinfo, buffer, 1);    //读取一行jpg图像数据到buffer
        memcpy(point, *buffer, width*depth);    //将buffer中的数据逐行给src_buff
        point += width * depth;            //指针偏移一行
    }

    jpeg_finish_decompress(&cinfo);//解压缩完毕
    jpeg_destroy_decompress(&cinfo);// 释放资源
    free(src_buff);//释放资源

    fclose(input_file);

}



程序中src_buff就是解码之后的位图数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值