유니티 텍스쳐 생성 (Unity Texture Create from bytes)

1. RenderTexture -> Texture2D -> bytes

    private void GetRenderTextureBytes()
    {
        // 매프레임 new를 해줄경우 메모리 문제 발생 -> 멤버 변수로 변경
        Texture2D txt = new Texture2D(texture.width, texture.height, TextureFormat.RGB24, false);
        RenderTexture.active = texture;
        txt.ReadPixels(new Rect(0, 0, texture.width, texture.height), 0, 0);
        txt.Apply();
        txtBytes = txt.EncodeToPNG();
    }


2. bytes -> Texture2D

    private Texture2D Base64ToTexture2D(byte[] imageData)
    {
     
        int width, height;
        GetImageSize(imageData, out width, out height);

        // 매프레임 new를 해줄경우 메모리 문제 발생 -> 멤버 변수로 변경
        Texture2D texture = new Texture2D(width, height, TextureFormat.ARGB32, false, true);

        texture.hideFlags = HideFlags.HideAndDontSave;
        texture.filterMode = FilterMode.Point;
        texture.LoadImage(imageData);
        texture.Apply();

        return texture;
    }
    private void GetImageSize(byte[] imageData, out int width, out int height)
    {
        width = ReadInt(imageData, 3 + 15);
        height = ReadInt(imageData, 3 + 15 + 2 + 2);
    }

    private int ReadInt(byte[] imageData, int offset)
    {
        return (imageData[offset] << 8 | imageData[offset + 1]);
    }



3. string -> byte[]
byte[] byteData = System.Convert.FromBase64String(stringData);
byte[] byteData = Encoding.ASCII.GetBytes(stringData);

4. byte[] -> string
string stringData = Encoding.ASCII.GetString(byteData, 0, count);
string stringData = System.Convert.ToBase64String(byteData);


5. //매프레임 new를 해주면 Could not allocate memory: System out of memory! 발생할 수 있다. 멤버 변수로 선언한뒤 한번만 new로 할당하고 사용하자.

댓글

이 블로그의 인기 게시물

유니티 네트워크 (Unity NetworkManager Component)

유니티 네트워크 (Unity Socket)