Unity截图成png格式保存到本地的三种方式
- 第一种截图方式,直接用unity自带截图函数ScreenCapture.CaptureScreenshot,全屏截图,不能改变图像尺寸.
- 第二种截图方式,将屏幕图像存储到一个texture2D中去,可以设定图片尺寸
- 第三种截图方式,将rendertexture存储到一个texture2D中去,可以设定图片尺寸
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class save : MonoBehaviour
{
private struct ImageData
{
public long timestamp;
public byte[] data;
}
[Tooltip("截图宽度px")]
public int width;
[Tooltip("截图高度py")]
public int height;
[Tooltip("截图存储路径")]
public string path;
public Camera cam;
public bool capture;
Texture2D mtexture;
RenderTexture rt;
Rect ret;
void Start()
{
if (cam == null)
{
cam = GetComponent<Camera>();
}
}
void Update()
{
if (Input.GetKeyUp(KeyCode.C))
{
if (!capture)
{
cam.enabled = true;
capture = true;
StartCoroutine(CaptureAndSave03());
Debug.Log("REC!");
}
else
{
cam.enabled = false;
capture = false;
StopCoroutine(CaptureAndSave03());
Debug.Log("REC STOP!");
}
}
}
public IEnumerator CaptureAndSave01()
{
while(capture)
{
ImageData pack;
pack.timestamp = System.DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
ScreenCapture.CaptureScreenshot(pack.timestamp + ".png");
yield return new WaitForSeconds(1);
}
}
public IEnumerator CaptureAndSave02()
{
while(capture)
{
yield return new WaitForEndOfFrame();
mtexture = new Texture2D(width, height, TextureFormat.RGB24, false);
ret.width = width;
ret.height = height;
mtexture.ReadPixels(ret, 0, 0);
mtexture.Apply();
ImageData pack;
pack.data = mtexture.EncodeToPNG();
pack.timestamp = System.DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
FileStream file = File.Create(pack.timestamp + ".png");
file.Write(pack.data, 0, pack.data.Length);
file.Close();
}
}
public IEnumerator CaptureAndSave03()
{
while(capture)
{
yield return new WaitForEndOfFrame();
rt = new RenderTexture(width, height, 0);
cam.targetTexture = rt;
cam.Render();
RenderTexture.active = rt;
mtexture = new Texture2D(width, height, TextureFormat.RGB24, false);
ret.width = width;
ret.height = height;
mtexture.ReadPixels(ret, 0, 0);
mtexture.Apply();
cam.targetTexture = null;
RenderTexture.active = null;
GameObject.Destroy(mtexture);
ImageData pack;
pack.data = mtexture.EncodeToPNG();
pack.timestamp = System.DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
FileStream file = File.Create(pack.timestamp + ".png");
file.Write(pack.data, 0, pack.data.Length);
file.Close();
}
}
}