| input | 要转换的原生数组。 | 
| format | 图像数据的像素格式。 | 
| width | 图像数据以像素为单位的宽度。 | 
| height | 图像数据以像素为单位的高度。 | 
| rowBytes | 单行以字节为单位的长度。默认值为 0,这意味着 Unity 会自动计算长度。 | 
将此原生数组编码为 PNG 格式。
此函数返回一个 NativeArray<byte>,它是 PNG 数据。您可以将编码后的数据存储为文件或在不进行进一步处理的情况下将其发送到网络。
此函数不适用于任何压缩格式。编码后的 PNG 数据将是 8 位灰度、RGB 或 RGBA(取决于传入的格式)。对于单通道红色纹理(R8、R16、RFloat 和 RHalf),编码后的 PNG 数据将为灰度。
PNG 数据不包含伽马校正或色彩配置文件信息。
此函数返回的原生数组使用持久分配器分配,因此此函数只能从主线程调用。
// Saves screenshot as PNG file. using System.Collections; using System.IO; using Unity.Collections; using UnityEngine;
public class PNGScreenSaver : MonoBehaviour { // Take a shot immediately IEnumerator Start() { yield return SaveScreenPNG(); }
IEnumerator SaveScreenPNG() { // Read the screen buffer after rendering is complete yield return new WaitForEndOfFrame();
// Create a texture in RGB24 format the size of the screen int width = Screen.width; int height = Screen.height; Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
// Read the screen contents into the texture tex.ReadPixels(new Rect(0, 0, width, height), 0, 0); tex.Apply();
// Encode the bytes in PNG format NativeArray<byte> imageBytes = new NativeArray<byte>(tex.GetRawTextureData(), Allocator.Temp); var bytes = ImageConversion.EncodeNativeArrayToPNG(imageBytes, tex.graphicsFormat, (uint)width, (uint)height); Object.Destroy(tex);
// Write the returned byte array to a file in the project folder File.WriteAllBytes(Application.dataPath + "/../SavedScreen.png", bytes.ToArray()); } }