Unity3d 技巧(6) -将RenderTexture保存成一张png图片

  public static bool saveMainTextureToPng(string filePath, Material mt)
    {
        Texture tex = mt.mainTexture;
        if (tex.GetType() != typeof(Texture2D))
        {
            return false;
        }
        Texture2D savedTexture = (Texture2D)tex;
        try
        {
            Texture2D newTexture = new Texture2D(savedTexture.width, savedTexture.height, TextureFormat.RGBA32, false);
            newTexture.SetPixels(0, 0, savedTexture.width, savedTexture.height, savedTexture.GetPixels());
            newTexture.Apply();
            byte[] bytes = newTexture.EncodeToPNG();
            if (bytes != null && bytes.Length > 0)
            {
                File.WriteAllBytes(filePath, bytes);
                Debug.Log("转换PNG成功:" + AssetDatabase.GetAssetPath(mt.mainTexture) + "-->" + savedTexture.format.ToString());
            }
        }
        catch (IOException ex)
        {
            Debug.Log("转换PNG失败:" + AssetDatabase.GetAssetPath(mt.mainTexture));
            return false;
        }

        return true;
    }





你可能感兴趣的:(Unity3d技巧)