yuv420sp_to_jpg C语言
时间: 2023-06-10 19:06:20 浏览: 143
下面是将yuv420sp格式的图像转换为jpeg格式的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <jpeglib.h>
void yuv420sp_to_jpg(unsigned char *yuv, int width, int height, char *filename) {
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
JSAMPROW row_pointer[1];
int row_stride;
FILE *outfile = fopen(filename, "wb");
if (outfile == NULL) {
fprintf(stderr, "Cannot open output file %s\n", filename);
return;
}
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
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, 90, TRUE);
jpeg_start_compress(&cinfo, TRUE);
row_stride = width * 3;
JSAMPLE *rgb = (JSAMPLE *)malloc(row_stride);
while (cinfo.next_scanline < cinfo.image_height) {
int y, u, v;
unsigned char *py, *pu, *pv;
py = yuv + cinfo.next_scanline * width;
pu = yuv + width * height + (cinfo.next_scanline >> 1) * width;
pv = yuv + width * height * 5 / 4 + (cinfo.next_scanline >> 1) * width;
for (int i = 0, j = 0; i < width; i += 2, j += 6) {
y = py[i];
u = pu[j] - 128;
v = pv[j] - 128;
rgb[i * 3] = (unsigned char)(y + 1.4075 * v);
rgb[i * 3 + 1] = (unsigned char)(y - 0.3455 * u - 0.7169 * v);
rgb[i * 3 + 2] = (unsigned char)(y + 1.779 * u);
y = py[i + 1];
rgb[(i + 1) * 3] = (unsigned char)(y + 1.4075 * v);
rgb[(i + 1) * 3 + 1] = (unsigned char)(y - 0.3455 * u - 0.7169 * v);
rgb[(i + 1) * 3 + 2] = (unsigned char)(y + 1.779 * u);
}
row_pointer[0] = rgb;
jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
free(rgb);
jpeg_finish_compress(&cinfo);
fclose(outfile);
jpeg_destroy_compress(&cinfo);
}
```
其中,yuv是yuv420sp格式的图像数据,width和height分别是图像的宽和高,filename是要保存的jpeg文件名。该函数使用libjpeg库将yuv420sp格式的图像数据转换为jpeg格式的图像数据,并保存到指定的文件中。具体的转换过程是将yuv数据转换为rgb数据,然后使用libjpeg库进行压缩编码。
阅读全文