tex | 要转换的纹理。 |
将此纹理编码为 PNG 格式。
此函数返回包含 PNG 文件数据的字节数组。您可以将编码的数据存储为文件,或在不经过进一步处理的情况下通过网络发送它。
此函数不适用于任何压缩格式。 Texture.isReadable 必须为 true
。
编码的 PNG 数据将为 8 位灰度、RGB 或 RGBA(具体取决于所传入的格式)。对于单通道红色纹理( R8
、R16
、RFloat
和 RHalf
),编码的 PNG 数据将为灰度。PNG 数据不包含伽玛校正或色彩配置文件信息。
// Saves screenshot as PNG file. using UnityEngine; using UnityEngine.Networking; 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 = ImageConversion.EncodeToPNG(tex); 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 var w = UnityWebRequest.Post("http://localhost/cgi-bin/env.cgi?post", form); yield return w.SendWebRequest();
if (w.result != UnityWebRequest.Result.Success) { Debug.Log(w.error); } else { Debug.Log("Finished Uploading Screenshot"); } } }