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.代码实现
namespace App.System
{
/// <summary>
/// 相机截图
/// </summary>
public class CamUI : MonoBehaviour
{
public Button takeBtn;
public RawImage imgCam;
public void Start()
{
takeBtn.onClick.AddListener(OnTakePicture);
}
#region 事件
private void OnTakePicture()
{
var dicPath = Application.streamingAssetsPath;
string path1 = dicPath + $"/VPImg/picture1.png";
SaveTexture(path1, (RenderTexture) imgCam.texture);
}
private void SaveTexture(string path, RenderTexture renderTexture)
{
var width = renderTexture.width;
var height = renderTexture.height;
Texture2D tex =
new Texture2D(width, height, TextureFormat.ARGB32, false); //创建空白贴图
var backupActive = RenderTexture.active;
RenderTexture.active = renderTexture; //将渲染贴图信息放入缓存
tex .ReadPixels(new Rect(0, 0, width, height), 0, 0); //复制缓存信息
tex .Apply();
RenderTexture.active = backupActive;
var bytes = tex .EncodeToPNG();//示例保存成png格式
File.WriteAllBytes(path, bytes);
}
#endregion
}
}