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;

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.