如何在 Unity 中 EncodeToPng 压缩纹理

How to EncodeToPng compressed Textures in Unity

我开发了一个保存纹理(屏幕截图)的应用程序,我需要压缩它们,但是 - 我不能使用 EncodeToPNG 方法在屏幕上显示图像。

我的步数:

  1. Texture2D tex = new Texture2D(recwidth, recheight, TextureFormat.RGB24, false); //RGB24- 因为下一步:

  2. tex.ReadPixels(rex, rdPXX, rdPXY); tex.Apply();

  3. tex.Compress(false);

稍后我需要用-

在屏幕上显示它
  1. var bytes = tex.EncodeToPNG();

但我不能,因为我们都知道 EncodeToPNG 不支持压缩纹理,所以我能做什么?在我的手机上需要很多 space

在使用 EncodeToPNG 之前,您必须先解压缩纹理。你应该可以用 RenderTexture 来做到这一点。将压缩后的 Texture2D 复制到 RenderTexture。将 RenderTexture 分配给 RenderTexture.active,然后使用 ReadPixels 将像素从 RenderTexture 复制到您希望采用解压缩格式的新 Texture2D。现在,您可以在上面使用 EncodeToPNG

执行此操作的辅助函数:

public static class ExtensionMethod
{
    public static Texture2D DeCompress(this 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;
    }
}

用法:

创建压缩纹理:

Texture2D tex = new Texture2D(recwidth, recheight, TextureFormat.RGB24, false);
tex.ReadPixels(rex, rdPXX, rdPXY);
tex.Apply();
tex.Compress(false);

从压缩的纹理创建一个新的解压纹理:

Texture2D decopmpresseTex = tex.DeCompress();

编码为 png

var bytes = decopmpresseTex.EncodeToPNG();