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();
}
}
}