示例#1
0
    public static byte[] TextureEncodeToPNG(this Texture @this, TextureConvert convert = TextureConvert.None,
                                            TextureFormat pngFormat = TextureFormat.RGBA32)
    {
        if (convert == TextureConvert.None)
        {
            if (@this is Texture2D)
            {
                var tex0           = @this as Texture2D;
                int channelsActual = tex0.format.Channels();
                int channelsExpect = pngFormat.Channels();
                if (!(channelsActual == channelsExpect || channelsActual == 3 && channelsExpect == 4))
                {
                    Debug.LogWarningFormat("Tex channels not match: \"{0}\",{1}, expect: {2}", tex0.name, tex0.format, pngFormat);
                }

                if (tex0.isReadable)
                {
                    return(tex0.EncodeToPNG());
                }
                else
                {
                    Texture2D tex2D = new Texture2D(tex0.width, tex0.height);
                    try
                    {
                        Graphics.CopyTexture(tex0, tex2D);
                        return(tex2D.EncodeToPNG());
                    }
                    finally
                    {
                        Util.DestroyRes(tex2D);
                    }
                }
            }
            else if (@this is RenderTexture)
            {
                Texture2D tex = ((RenderTexture)@this).ToNewTexture2D(pngFormat);
                try
                {
                    return(tex.EncodeToPNG());
                }
                finally
                {
                    Util.DestroyRes(tex);
                }
            }
            else
            {
                throw new NotSupportedException();
            }
        }
        else
        {
            RenderTexture rt         = null;
            Material      convertMat = null;
            try
            {
                rt         = RenderTexture.GetTemporary(@this.width, @this.height);
                convertMat = new Material(Shader.Find("Hidden/ColorSpaceConvert"));
                Graphics.Blit(@this, rt, convertMat, convert == TextureConvert.LinearToGamma ? 0 : 1);
                return(rt.TextureEncodeToPNG(TextureConvert.None, pngFormat));
            }
            finally
            {
                RenderTexture.ReleaseTemporary(rt);
                Util.DestroyRes(convertMat);
            }
        }
    }