【背景】
之前两篇帖子介绍了如何在Unity中捕捉360度全景,以及如何将CubeMap转换为平面2D对象。今天进一步来介绍一下,如何将2D全景对象存储为JPG或其它格式的图片文件。
【思路】要将只有Unity能够识别的RenderTexture2D对象转换为通用的JPG格式文件,做的一个工作就是内码转换,也就是将2D对象还原成字节信息,再通过字节信息流转换为JPG格式文件写入磁盘指定位置。
【具体脚本】在之前写的Capture脚本中增加一个Save函数,给这个Save函数传上一步捕捉到的RenderTexture2D对象equirectRT:
public void Capture()
{
targetCamera.RenderToCubemap(cubeMapLeft);
cubeMapLeft.ConvertToEquirect(equirectRT);
Save(equirectRT);
}
Save函数内部实现将equirectRT转换为Bytes信息流然后写入磁盘JPG的行为。
public void Save(RenderTexture rt)
{
Texture2D tex = new Texture2D(rt.width, rt.height);
RenderTexture.active = rt;
tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
RenderTexture.active = null;
byte[] bytes = tex.EncodeToJPG();
string path = Application.dataPath + "/Panorama" + ".jpg";
System.IO.File.WriteAllBytes(path,bytes);
}
【测试】
保存上述脚本后运行游戏,点击Space测试,会发现有一个JPG文件存储在项目文件夹中。