使用libjpeg-turbo处理YUV444P和YUV420P格式

今天用libjpeg-turbo写了一个windows版的程序,可以将YUV444P或者YUV420P格式的数据压缩为jpg文件,也可以将jpg文件还原为YUV444P或者YUV420P的数据。代码上传到了github。喜欢的请给个星星,谢谢!
代码参考了这里

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
1. 首先安装libjpeg-turbo库,可以通过以下命令进行安装: ``` sudo apt-get install libjpeg-turbo8-dev ``` 2. 在程序中添加以下头文件: ``` #include <jpeglib.h> ``` 3. 定义一个结构体变量来存储压缩后的JPEG数据: ``` struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; ``` 4. 初始化JPEG压缩对象: ``` cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); ``` 5. 设置JPEG压缩参数: ``` cinfo.image_width = width; cinfo.image_height = height; cinfo.input_components = 3; cinfo.in_color_space = JCS_YCbCr; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE); ``` 其中,width和height分别为图像的宽度和高度,quality为压缩质量,取值范围为0-100,0为最差质量,100为最好质量。 6. 设置输出文件: ``` FILE *outfile = fopen(output_file, "wb"); jpeg_stdio_dest(&cinfo, outfile); ``` 7. 开始压缩: ``` jpeg_start_compress(&cinfo, TRUE); JSAMPROW row_pointer[1]; int row_stride; row_stride = width * 3; unsigned char *yuv_data = (unsigned char *)malloc(width * height * 3); // 将YUV数据转换成JPEG数据 for (int i = 0; i < height; i++) { row_pointer[0] = &yuv_data[i * width * 3]; jpeg_write_scanlines(&cinfo, row_pointer, 1); } ``` 其中,row_stride为每行数据的字节数,yuv_data为存储YUV数据的数组。 8. 压缩结束,释放内存: ``` jpeg_finish_compress(&cinfo); fclose(outfile); jpeg_destroy_compress(&cinfo); free(yuv_data); ``` 完整代码示例: ``` #include <stdio.h> #include <stdlib.h> #include <jpeglib.h> void yuv_to_jpeg(unsigned char *yuv_data, int width, int height, int quality, const char *output_file) { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); FILE *outfile = fopen(output_file, "wb"); jpeg_stdio_dest(&cinfo, outfile); cinfo.image_width = width; cinfo.image_height = height; cinfo.input_components = 3; cinfo.in_color_space = JCS_YCbCr; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE); jpeg_start_compress(&cinfo, TRUE); JSAMPROW row_pointer[1]; int row_stride; row_stride = width * 3; for (int i = 0; i < height; i++) { row_pointer[0] = &yuv_data[i * width * 3]; jpeg_write_scanlines(&cinfo, row_pointer, 1); } jpeg_finish_compress(&cinfo); fclose(outfile); jpeg_destroy_compress(&cinfo); free(yuv_data); } int main() { // 读取YUV数据 int width = 1920; int height = 1080; unsigned char *yuv_data = (unsigned char *)malloc(width * height * 3); FILE *fp = fopen("input.yuv", "rb"); fread(yuv_data, 1, width * height * 3, fp); fclose(fp); // 转换成JPEG yuv_to_jpeg(yuv_data, width, height, 80, "output.jpg"); return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值