用C语言给出一个YUV转jpg
时间: 2023-08-30 16:06:47 浏览: 44
这里给出一个简单的YUV转JPEG的示例代码,使用了libjpeg库:
```c
#include <stdio.h>
#include <stdlib.h>
#include <jpeglib.h>
void YUV2RGB(int y, int u, int v, unsigned char *r, unsigned char *g, unsigned char *b) {
int c = y - 16, d = u - 128, e = v - 128;
*r = (unsigned char)(298 * c + 409 * e + 128 >> 8);
*g = (unsigned char)(298 * c - 100 * d - 208 * e + 128 >> 8);
*b = (unsigned char)(298 * c + 516 * d + 128 >> 8);
}
int main() {
int width = 640, height = 480;
FILE *fpIn = fopen("input.yuv", "rb");
unsigned char *yuvData = (unsigned char*)malloc(width * height * 3 / 2);
fread(yuvData, 1, width * height * 3 / 2, fpIn);
unsigned char *rgbData = (unsigned char*)malloc(width * height * 3);
unsigned char *r, *g, *b;
int y, u, v;
for (int i = 0; i < width * height; i++) {
y = yuvData[i];
u = yuvData[width * height + (i >> 2) * (width >> 1) + (i & 1) * (i & 2)];
v = yuvData[width * height * 5 / 4 + (i >> 2) * (width >> 1) + (i & 1) * (i & 2)];
r = &rgbData[i * 3];
g = &rgbData[i * 3 + 1];
b = &rgbData[i * 3 + 2];
YUV2RGB(y, u, v, r, g, b);
}
FILE *fpOut = fopen("output.jpg", "wb");
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
jpeg_stdio_dest(&cinfo, fpOut);
cinfo.image_width = width;
cinfo.image_height = height;
cinfo.input_components = 3;
cinfo.in_color_space = JCS_RGB;
jpeg_set_defaults(&cinfo);
jpeg_start_compress(&cinfo, TRUE);
JSAMPROW row_pointer[1];
while (cinfo.next_scanline < cinfo.image_height) {
row_pointer[0] = &rgbData[cinfo.next_scanline * cinfo.image_width * 3];
jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
free(yuvData);
free(rgbData);
fclose(fpIn);
fclose(fpOut);
return 0;
}
```
这个程序将从文件input.yuv中读入YUV数据,然后将其转换为RGB格式,并使用libjpeg库将RGB图像压缩为JPEG格式,并保存到文件output.jpg中。在此示例代码中,我们使用了一个简单的YUV到RGB的转换函数YUV2RGB,它将Y、U、V三个分量转换为RGB三个分量。具体的转换算法可以参考YUV到RGB的转换公式。
注意,此示例代码仅用于演示YUV到JPEG的转换过程,实际应用中可能需要更加完善的异常处理和错误检查机制。