Texture2D.EncodeToPNG的Unity幫助頁面有一個捕獲和上傳屏幕截圖的完整示例。
http://docs.unity3d.com/ScriptReference/Texture2D.EncodeToPNG.html
// Saves screenshot as PNG file.
using UnityEngine;
using System.Collections;
using System.IO;
public class PNGUploader : MonoBehaviour {
// Take a shot immediately
IEnumerator Start() {
yield return UploadPNG();
}
IEnumerator UploadPNG() {
// We should only read the screen buffer after rendering is complete
yield return new WaitForEndOfFrame();
// Create a texture the size of the screen, RGB24 format
int width = Screen.width;
int height = Screen.height;
Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
// Read screen contents into the texture
tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
tex.Apply();
// Encode texture into PNG
byte[] bytes = tex.EncodeToPNG();
Object.Destroy(tex);
// For testing purposes, also write to a file in the project folder
// File.WriteAllBytes(Application.dataPath + "/../SavedScreen.png", bytes);
// Create a Web Form
WWWForm form = new WWWForm();
form.AddField("frameCount", Time.frameCount.ToString());
form.AddBinaryData("fileUpload",bytes);
// Upload to a cgi script
WWW w = new WWW("http://localhost/cgi-bin/env.cgi?post", form);
yield return w;
if (w.error != null) {
Debug.Log(w.error);
} else {
Debug.Log("Finished Uploading Screenshot");
}
}
}
好,冬暖夏涼。我將該代碼放入新的cs文件並將其附加到保存按鈕。我在腳本的頂部看到'IEnumerator Start()'。這是否意味着它應該在應用程序啓動後立即運行?在事情成功或失敗的時刻,我沒有在控制檯中得到任何反饋。我需要做什麼來執行這個腳本? – greyBow
是的,啓動意味着它在啓動時立即運行。要附加到一個按鈕,您需要刪除啓動功能,並將以下內容替換爲: 'void TakeScreenshot(){ StartCoroutine(「UploadPNG」); }' 之後,將按鈕的OnClick處理程序附加到檢查器中的TakeScreenshot。當然,您仍然需要將您的特定上傳邏輯編碼到您自己的URL,因爲它當前正在將數據發送到示例URL。 –