RawImage保存图片

 

 

using System.IO;
using UnityEngine;
using UnityEngine.UI;

public class SaveRawImageAsPNG : MonoBehaviour
{
    public RawImage rawImage;

    public void SaveImage()
    {
        if (rawImage.texture is Texture2D texture2D)
        {
            // 如果RawImage.texture已经是Texture2D,则直接编码并保存
            byte[] bytes = texture2D.EncodeToPNG();
            string filePath = "image.png";
            File.WriteAllBytes(filePath, bytes);
            Debug.Log("Image saved to " + filePath);
        }
        else if (rawImage.texture is RenderTexture renderTexture)
        {
            // 如果RawImage.texture是RenderTexture,则需要转换为Texture2D
            Texture2D tempTexture2D = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.ARGB32, false);
            RenderTexture.active = renderTexture;
            tempTexture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
            tempTexture2D.Apply();

            byte[] bytes = tempTexture2D.EncodeToPNG();
            string filePath = "image.png";
            File.WriteAllBytes(filePath, bytes);
            Debug.Log("Image saved to " + filePath);

            // 清理
            RenderTexture.active = null;
            Destroy(tempTexture2D);
        }
        else
        {
            Debug.LogError("Unsupported texture type for saving.");
        }
    }
}

 

 

#################################

posted @ 2024-08-01 15:25  西北逍遥  阅读(10)  评论(0编辑  收藏  举报