Unity将相机内容输出成图片
生活随笔
收集整理的這篇文章主要介紹了
Unity将相机内容输出成图片
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Unity自帶Recorder
之所以要講Recorder,是因為Recorder的錄像功能實際上就是把屏幕圖像保存成了一幀幀的圖片,而實現的功能,所以我們先看下它的源碼。
public override void RecordFrame(RecordingSession session){if (m_Inputs.Count != 1)throw new Exception("Unsupported number of sources");Texture2D tex = null;if (m_Inputs[0] is GameViewInput)//游戲視窗輸出的圖像{tex = ((GameViewInput)m_Inputs[0]).image;if (m_Settings.outputFormat == ImageRecorderOutputFormat.EXR){var textx = new Texture2D(tex.width, tex.height, TextureFormat.RGBAFloat, false);textx.SetPixels(tex.GetPixels());tex = textx;}else if (m_Settings.outputFormat == ImageRecorderOutputFormat.PNG){var textx = new Texture2D(tex.width, tex.height, TextureFormat.RGB24, false);textx.SetPixels(tex.GetPixels());//直接復制像素信息tex = textx;}}else{var input = (BaseRenderTextureInput)m_Inputs[0];//普通渲染貼圖var width = input.outputRT.width;var height = input.outputRT.height;tex = new Texture2D(width, height, m_Settings.outputFormat != ImageRecorderOutputFormat.EXR ? TextureFormat.RGBA32 : TextureFormat.RGBAFloat, false);var backupActive = RenderTexture.active;RenderTexture.active = input.outputRT;//將貼圖信息輸入到緩存中tex.ReadPixels(new Rect(0, 0, width, height), 0, 0, false);//讀取緩存的像素tex.Apply();//保存應用RenderTexture.active = backupActive;}byte[] bytes;switch (m_Settings.outputFormat)//輸出格式{case ImageRecorderOutputFormat.PNG:bytes = tex.EncodeToPNG();break;case ImageRecorderOutputFormat.JPEG:bytes = tex.EncodeToJPG();break;case ImageRecorderOutputFormat.EXR:bytes = tex.EncodeToEXR();break;default:throw new ArgumentOutOfRangeException();}if(m_Inputs[0] is BaseRenderTextureInput || m_Settings.outputFormat != ImageRecorderOutputFormat.JPEG)UnityHelpers.Destroy(tex);var path = m_Settings.fileNameGenerator.BuildAbsolutePath(session);File.WriteAllBytes( path, bytes);//保存到本地文件}仿照進行功能實現
1.創建一個相機,將拍攝的圖片保存到RenderTexture上
2.代碼實現
總結
以上是生活随笔為你收集整理的Unity将相机内容输出成图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 软件测试流程图Bug管理流程图
- 下一篇: 深入解析内存原理:RAM的基本原理