使用libjpeg-turbo yuv转换成jpeg
时间: 2023-08-29 07:12:26 浏览: 280
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;
}
```
阅读全文