unity中Sprite、Texture2D和bytes[]的转换

从流数据转成Sprite,需要使用Texture2D作为中转

1、从sprite 转换到bytes[]

        
    public byte[] GetByte(Sprite sp)
    {
        //转换成Texture
        Texture2D temp = sp.texture;
        //在转换成bytes
        byte[] photoByte = temp.EncodeToPNG();
        return photoByte;
    }

2、从bytes[] 转换到Sprite

    public Sprite GetSprite(Byte[] bytes)
    {
        //先创建一个Texture2D对象,用于把流数据转成Texture2D
        Texture2D texture = new Texture2D(10, 10);
        texture.LoadImage(bytes);//流数据转换成Texture2D
        //创建一个Sprite,以Texture2D对象为基础
        Sprite sp = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
        return sp;
    }

 

你可能感兴趣的:(unity)