- Home /
Loading Base64 String into RawImage
Hello, everyone!
I'm trying to load a base64 string to my instantiated prefab's RawImage. When i check the texture of the RawImage, it shows a red question mark. but the RawImage in my scene still remains black (default color i had set)
Here is my code:
Texture2D convertedBase64String = new Texture2D (2,2);
string iconBase64String = "base64 string here"; // string works when converted using online converter
byte[] decodedBytes = System.Text.Encoding.UTF8.GetBytes(iconBase64String);
convertedBase64String.LoadImage(decodedBytes);
// Instantiated object
appButton.transform.Find("Icon").GetComponent<RawImage>().texture = convertedBase64String;
So in the comments you are saying that you get the desired behavior, when an online converter creates a base64 string for you?
Have you checked out these methods?
System.Convert.ToBase64String(byte[] bytes)
System.Convert.FromBase64String(byte[] bytes)
Yes I have. When I replace System.Text.Encoding.UTF8.GetBytes with System.Convert.FromBase64String, I get an error that says "System.FormatException: Invalid length."
It sounds like that string you passed in was not a Base64 string. A Base64 string cannot be any arbitrary size or contain any characters.
Okay, so using ToBase64 is not used on its own. You use it in conjunction with UTF8 encoding, for example.
To clarify: UTF8 deter$$anonymous$$es how the characters of a string are encoded into bytes. A base 64 string deter$$anonymous$$es how to encode those bytes into characters that you can easily transfer over the wire (no sequence control character, etc. are contained in that string).
Check out the following link to see how to create Base64 strings from arbitrary string and backwards again:
https://arcanecode.com/2007/03/21/encoding-strings-to-base64-in-c/
If you show more of your code where you get the string from, I could help further.
Thanks for clarifying that up! I use base64-image.de to convert my images.
Answer by Bunny83 · May 16, 2017 at 08:55 AM
You can't assign a byte array of arbitrary image data to a variable that expects a class instance of type Texture. You have to create a Texture2D object and make it load the image from your data.
Texture2D tex = new Texture2D(1,1);
tex.LoadImage( decodedBytes );
appButton.transform.Find("Icon").GetComponent<RawImage>().texture = tex;
Note that base64 is just a way to encode arbitrary bytes into a human readable datastream. When you decode the data stream you get back the original byte array. Those bytes could contain any kind of data.
Unity only supports loading JPG and PNG files at runtime. So make sure you image is in one of those two formats or it can't be loaded.