在做视频渲染的时候经常需要将中间的yuv数据保存到文件中进行查看,下面的方法介绍了如何将yuv420p的数据写入到文件中:
bool saveYuvFile(const std::string& filename, const uint8_t* yuvData, size_t width, size_t height)
{
std::ofstream file(filename, std::ios::binary);
if (!file)
{
return false;
}
size_t ySize = width * height;
size_t uvSize = (width / 2) * (height / 2);
// Reserve space for YUV data to avoid multiple reallocations
file.seekp(ySize + uvSize * 2 - 1);
file.write("", 1);
file.seekp(0);
// Write YUV data directly to the file
file.write(reinterpret_cast<const char*>(yuvData), ySize + uvSize * 2);
file.close();
return true;
}