libjpeg YUV转jpeg
时间: 2023-05-27 08:06:16 浏览: 131
YUV转JPG 程序
5星 · 资源好评率100%
要将YUV图像转换为JPEG图像,需要使用libjpeg库。下面是一个简单的示例代码:
```c
#include <stdio.h>
#include <jpeglib.h>
#define WIDTH 640
#define HEIGHT 480
void yuv_to_rgb(unsigned char *yuv, unsigned char *rgb) {
int y = yuv[0], u = yuv[1], v = yuv[2];
int r = y + 1.402 * (v - 128);
int g = y - 0.34414 * (u - 128) - 0.71414 * (v - 128);
int b = y + 1.772 * (u - 128);
rgb[0] = (unsigned char)r;
rgb[1] = (unsigned char)g;
rgb[2] = (unsigned char)b;
}
void yuv_to_jpeg(unsigned char *yuv_data, unsigned char *jpeg_data, int quality) {
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
JSAMPROW row_pointer[1];
int row_stride;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
jpeg_mem_dest(&cinfo, &jpeg_data, &jpeg_size);
cinfo.image_width = WIDTH;
cinfo.image_height = HEIGHT;
cinfo.input_components = 3;
cinfo.in_color_space = JCS_RGB;
jpeg_set_defaults(&cinfo);
jpeg_set_quality(&cinfo, quality, TRUE);
jpeg_start_compress(&cinfo, TRUE);
unsigned char rgb_data[WIDTH * HEIGHT * 3];
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
int i = y * WIDTH + x;
yuv_to_rgb(yuv_data + i * 3, rgb_data + i * 3);
}
row_pointer[0] = &rgb_data[y * WIDTH * 3];
row_stride = WIDTH * 3;
jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
}
int main() {
unsigned char yuv_data[WIDTH * HEIGHT * 3];
// 从文件或摄像头等读取YUV数据
unsigned char jpeg_data[WIDTH * HEIGHT * 3];
yuv_to_jpeg(yuv_data, jpeg_data, 80);
// 将JPEG数据写入文件或发送到网络等
return 0;
}
```
该代码将YUV图像转换为RGB图像,然后使用libjpeg库将RGB图像压缩为JPEG格式。在`yuv_to_jpeg`函数中,首先创建一个`jpeg_compress_struct`结构体,并设置压缩参数。然后,将RGB图像逐行写入JPEG文件,最后完成压缩并销毁压缩结构体。
阅读全文