Texture2D转字节数组出错 (Unsupported texture format - Texture2D::EncodeTo functions do not support ……)

报错信息:

一、首先要将你需转成字节数组的Texture设置为可读写

勾上

二、此时可能会报下列错误

Unsupported texture format - Texture2D::EncodeTo functions do not support compressed texture formats.

UnityEngine.ImageConversion:EncodeToPNG(Texture2D)


    public static void SaveTexture2DToPngFile(Texture2D tex, string filePath)
    {
        byte[] data = tex.EncodeToPNG();
        File.WriteAllBytes(filePath, data);

#if UNITY_EDITOR
        AssetDatabase.Refresh();
#endif
    }

    public static void SaveTexture2DToPngFile_(Texture2D tex, string filePath)
    {
        byte[] data = DeCompress(tex).EncodeToPNG();
        File.WriteAllBytes(filePath, data);

#if UNITY_EDITOR
        AssetDatabase.Refresh();
#endif
    }

    public static Texture2D DeCompress(Texture2D source)
    {
        RenderTexture renderTex = RenderTexture.GetTemporary(
                    source.width,
                    source.height,
                    0,
                    RenderTextureFormat.Default,
                    RenderTextureReadWrite.Linear);

        Graphics.Blit(source, renderTex);
        RenderTexture previous = RenderTexture.active;
        RenderTexture.active = renderTex;
        Texture2D readableText = new Texture2D(source.width, source.height);
        readableText.ReadPixels(new Rect(0, 0, renderTex.width, renderTex.height), 0, 0);
        readableText.Apply();
        RenderTexture.active = previous;
        RenderTexture.ReleaseTemporary(renderTex);
        return readableText;
    }

猜你喜欢

转载自blog.csdn.net/m1234567q/article/details/128621014