mfc 中ffmpeg yuy2字节流转图片完整代码
时间: 2023-07-09 21:38:17 浏览: 274
以下是将 YUY2 格式的字节流转换为图片的完整 MFC 代码:
```c++
#include <iostream>
#include <fstream>
#include "stdafx.h"
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
}
#define INPUT_FILE_NAME "test.yuy2"
#define OUTPUT_FILE_NAME "test.jpg"
#define WIDTH 640
#define HEIGHT 480
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
// 初始化 FFmpeg
av_register_all();
// 打开输入文件
std::ifstream inputFile(INPUT_FILE_NAME, std::ios::binary | std::ios::ate);
if (!inputFile.is_open()) {
std::cerr << "Could not open input file: " << INPUT_FILE_NAME << std::endl;
return -1;
}
int inputSize = inputFile.tellg();
uint8_t *inputData = new uint8_t[inputSize];
inputFile.seekg(0, std::ios::beg);
inputFile.read((char*)inputData, inputSize);
inputFile.close();
// 创建 AVFrame 和 AVPicture
AVFrame *pFrame = av_frame_alloc();
AVPicture picture;
avpicture_alloc(&picture, AV_PIX_FMT_YUV422P, WIDTH, HEIGHT);
// 填充 AVFrame
pFrame->data[0] = inputData;
pFrame->data[1] = pFrame->data[0] + WIDTH * HEIGHT * 2 / 4;
pFrame->data[2] = pFrame->data[1];
pFrame->linesize[0] = WIDTH * 2;
pFrame->linesize[1] = WIDTH;
pFrame->linesize[2] = WIDTH;
// 将 AVFrame 转换为 AVPicture
struct SwsContext *sws_ctx = sws_getContext(WIDTH, HEIGHT, AV_PIX_FMT_YUYV422, WIDTH, HEIGHT, AV_PIX_FMT_YUV422P, 0, NULL, NULL, NULL);
sws_scale(sws_ctx, pFrame->data, pFrame->linesize, 0, HEIGHT, picture.data, picture.linesize);
// 保存为图片
AVCodec *pCodec = avcodec_find_encoder(AV_CODEC_ID_MJPEG);
AVCodecContext *pCodecCtx = avcodec_alloc_context3(pCodec);
pCodecCtx->pix_fmt = AV_PIX_FMT_YUVJ422P;
pCodecCtx->width = WIDTH;
pCodecCtx->height = HEIGHT;
pCodecCtx->time_base.num = 1;
pCodecCtx->time_base.den = 25;
avcodec_open2(pCodecCtx, pCodec, NULL);
AVPacket pkt;
av_init_packet(&pkt);
pkt.data = NULL;
pkt.size = 0;
int got_packet = 0;
avcodec_encode_video2(pCodecCtx, &pkt, &picture, &got_packet);
if (got_packet) {
FILE *fp = fopen(OUTPUT_FILE_NAME, "wb");
fwrite(pkt.data, 1, pkt.size, fp);
fclose(fp);
}
avcodec_close(pCodecCtx);
av_free(pCodecCtx);
av_free_packet(&pkt);
// 释放资源
avpicture_free(&picture);
av_frame_free(&pFrame);
sws_freeContext(sws_ctx);
delete[] inputData;
return 0;
}
```
这段代码利用了 C++ 的 ifstream 类读取 YUY2 格式的字节流数据,并将其转换为 JPEG 格式的图片。需要注意的是,这里使用了 FFmpeg 中的 libswscale 库进行图像转换。
阅读全文