Texture2D Base64 En-/Decoding

Hey there,

does anyone has a solution to Encode a Texture2D to a string in base64-format and vise versa?

Best regards from Germany and happy weekend.

Diversity

1 Like

This is untested, but I think the way to go would be something along the lines of:

//encode:
Texture2D tex; //assign in Inspector, load from Resources or WebRequest or what have you
byte[] imageBytes = tex.EncodeToPNG(); //encode to byte[]; you may also use EncodeToJPG()
string base64Image = System.Convert.ToBase64String(imageBytes, 0, imageBytes.Length); //byte[] to base64 string (params: byte[], array offset, number of bytes to encode)

//decode:
string base64Image; //again, obtain however
byte[] imageBytes = System.Convert.FromBase64String(base64Image); //base64 string to byte[]
Texture2D tex = new Texture2D(1, 1); //create a new texture; size doesn't matter. Set other options as needed either here, or after the next line
tex.LoadImage(imageBytes); //load the byte[] into the Texture

Hope this works, or at least helps a bit! Cheers!

1 Like

Hello Senshi,

thank you a lot. I wish you a nice day and a wonderful weekend.

Best regards.

1 Like