Unity Texture2D byte[] sprit转换

先将个笑话: Sprite 转 Texture

Sprite.texture;//蓦然回首才发现自行车就放在那里,之前还傻傻的到处去找方法来转😂

Texture2D 转byte[]

//如果你想复制一张图片 就把注释打开 更改返回值就可以了
    private byte[] duplicateTexture(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();
        //这里可以转 JPG PNG EXR  Unity都封装了固定的Api
        //byte[] bytes = readableText.EncodeToPNG();
        byte[] bytes = readableText.EncodeToJPG();
        return bytes;
        //RenderTexture.active = previous;
        //RenderTexture.ReleaseTemporary(renderTex);
        //return readableText;
    }

好像不用那么多行,一句"byte[] bytes = Texture2d.EncodeToJPG();"就行了🤣

sprite转byte[]

需要使用Texture2D作为中转

publi byte[] GetByte(Sprite sp)

{

        // 转换成Texture

        Texture2D temp = sp.texture;

        // 在转换成byte[]

        byte[] photoByte = temp.EncodeToPNG();

        return photoByte;

}

**

Byte[]转换到Sprite

**

public Sprite GetSprite(Byte[] bytes)

{

        Texture2D texture = new Texture2D(10,10);   // 先创建一个Texture2D对象,用于把流数据转成Texture2D

        texture.LoadImage(bytes);        // 流数据转换成Texture2D

        // 创建一个Sprite,以Texture2D对象为基础

        Sprite sp = Sprite.Create(texture,new Rect(0,0,texture.width,texture.height),vector2.zero);
        return sp;

}

参考链接:1.https://www.codeleading.com/article/3083916701/
2.https://www.jianshu.com/p/57a78c9a4985

posted @ 2022-06-22 18:05  哒哒哒~~~  阅读(918)  评论(0编辑  收藏  举报