如何在 Unity 中 EncodeToPng 压缩纹理 [英] How to EncodeToPng compressed Textures in Unity

查看:76
本文介绍了如何在 Unity 中 EncodeToPng 压缩纹理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I develop an app that saves textures (screenshots) and I need to compress them, but then- I can't use EncodeToPNG method in order to show the image on the screen.

我的步骤:

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

  1. Texture2D tex = new Texture2D(recwidth, recheight, TextureFormat.RGB24, false); //RGB24- Because of the next step:

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

稍后我需要将它显示在屏幕上 -

Later I need to show it on the screen with-

  1. var bytes = tex.EncodeToPNG();

但我不能,因为众所周知EncodeToPNG 不支持压缩纹理,那我该怎么办?我的手机占用了很多空间

But I can't because as we all know EncodeToPNG doesn't support compressed textures, so what can I do? It takes a lot of space on my mobile

推荐答案

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

You have to decompress the Texture first before using EncodeToPNG on it. You should be able to do this with RenderTexture. Copy the compressed Texture2D to RenderTexture. Assign the RenderTexture to RenderTexture.active then use ReadPixels to copy the pixels from the RenderTexture to the new Texture2D you wish to be in decompressed format. Now, you can use EncodeToPNG on it.

执行此操作的辅助函数:

The helper function to do this:

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);

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

Create a new decompressed Texture from the compressed Texture:

Texture2D decopmpresseTex = tex.DeCompress();

编码为png

var bytes = decopmpresseTex.EncodeToPNG();

这篇关于如何在 Unity 中 EncodeToPng 压缩纹理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆