我正在尝试将Unity项目的帧保存为自动生成预览Gif。我在我的脚本中调用这个方法如下:
Application.CaptureScreenshot("Screenshot" + Time.frameCount + ".png");
如果我在Unity中这样做,它可以正常工作。但是,当我将我的项目构建为WebGL时,它不再这样做了。为什么?或者有没有人知道保存帧的不同方式?
还有其他方法可以截取屏幕截图。没有在WebGL上测试,但你应该尝试一下。
void CaptureScreenshot()
{
StartCoroutine(CaptureScreenshotCRT());
}
IEnumerator CaptureScreenshotCRT()
{
yield return new WaitForEndOfFrame();
string path = Application.persistentDataPath + "/Screenshot" + Time.frameCount + ".png";
Texture2D screenImage = new Texture2D(Screen.width, Screen.height);
//Get Image from screen
screenImage.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
screenImage.Apply();
//Convert to png
byte[] imageBytes = screenImage.EncodeToPNG();
//Save image to file
System.IO.File.WriteAllBytes(path, imageBytes);
}
使用ScreenCapture.CaptureScreenshotAsTexture函数:
void CamptureScreenShot(){
yield return new WaitForEndOfFrame();
Texture2D texture = ScreenCapture.CaptureScreenshotAsTexture(1);
byte[] bytes = texture.EncodeToPNG();
}
然后您可以对图像执行某些操作:例如将其保存到服务器
void SaveFunction(byte[] bytes){
string imageName = username + "_" + date + ".png";
WWWForm form = new WWWForm();
form.AddField("frameCount", Time.frameCount.ToString());
form.AddBinaryData("file", bytes, imageName, "image/png");
using (UnityWebRequest request = UnityWebRequest.Post("my url service", form))
{
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
Debug.Log(request.error);
}
else
{
Debug.Log("Saved");
}
}
}