使用libjpeg 将yuv图像转换成jpeg文件
时间: 2023-05-27 20:06:19 浏览: 349
1. 首先需要安装libjpeg库,可以使用命令行进行安装:
```
sudo apt-get install libjpeg-dev
```
2. 然后创建一个C文件,例如convert.c,包含以下代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <jpeglib.h>
int main(int argc, char *argv[]) {
if (argc != 4) {
fprintf(stderr, "Usage: %s <input_yuv_file> <width> <height>\n", argv[0]);
exit(EXIT_FAILURE);
}
char *input_file = argv[1];
int width = atoi(argv[2]);
int height = atoi(argv[3]);
FILE *fp_in = fopen(input_file, "rb");
if (fp_in == NULL) {
fprintf(stderr, "Error opening input file: %s\n", input_file);
exit(EXIT_FAILURE);
}
FILE *fp_out = fopen("output.jpg", "wb");
if (fp_out == NULL) {
fprintf(stderr, "Error creating output file\n");
exit(EXIT_FAILURE);
}
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
jpeg_stdio_dest(&cinfo, fp_out);
cinfo.image_width = width;
cinfo.image_height = height;
cinfo.input_components = 3;
cinfo.in_color_space = JCS_YCbCr;
jpeg_set_defaults(&cinfo);
jpeg_start_compress(&cinfo, TRUE);
JSAMPROW row_pointer[1];
row_pointer[0] = malloc(width * 3);
int y, u, v;
unsigned char *buffer = malloc(width * height * 3);
fread(buffer, width * height * 3, 1, fp_in);
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
y = buffer[(i * width + j) * 3];
u = buffer[(i * width + j) * 3 + 1];
v = buffer[(i * width + j) * 3 + 2];
row_pointer[0][j * 3] = y;
row_pointer[0][j * 3 + 1] = u;
row_pointer[0][j * 3 + 2] = v;
}
jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
fclose(fp_in);
fclose(fp_out);
return 0;
}
```
3. 编译上述代码,可以使用以下命令:
```
gcc -o convert convert.c -ljpeg
```
4. 运行程序,命令格式为:
```
./convert <input_yuv_file> <width> <height>
```
其中,input_yuv_file为需要转换的YUV图像文件,width和height为图像的宽度和高度。
例如,转换名为test.yuv的图像,宽度为640,高度为480,可以使用以下命令:
```
./convert test.yuv 640 480
```
5. 转换后的JPEG文件将保存在当前目录下的output.jpg中。
阅读全文