How can I make a sprite from a byte array?

Viewed 2435

I have a Unity game where the player gets one's inventory from the database after starting the game. I got the pictures of items stored in Firebase Storage, and I can download them. However, I don't know how to make sprites from the byte[] (fileContents) I get by downloading. (I'd load these sprites in the player's inventory later)

I got the following C# script:

private void getPlayersInventory()
{
  FirebaseDatabase.DefaultInstance.GetReference("users").Child(auth.CurrentUser.UserId)
    .Child("inventory").GetValueAsync().ContinueWith(task => 
    {
      if (task.IsFaulted)
      {
        print("unable to get snapshot for the inventory");
      } 
      else if (task.IsCompleted) 
      {
        snapshot = task.Result;
        if(snapshot.HasChildren) 
        {
          foreach(var current in snapshot.Children)
          {
            string currentName = current.Value.ToString();
            print(currentName.ToLower() + ".png");
            const long maxAllowedSize = 10 * 1024 * 1024;
            storageReference.Child(currentName.ToLower() + ".png")
              .GetBytesAsync(maxAllowedSize)
              .ContinueWith((Task<byte[]> task_) => 
              {
                if (task_.IsFaulted || task_.IsCanceled) 
                {
                    Debug.Log(task_.Exception.ToString());
                } 
                else 
                {
                    byte[] fileContents = task_.Result;
                    Debug.Log("Finished downloading!");
                }
              });
          }
        }
      }
    });
}
1 Answers

I believe that you're looking for ImageConversion.LoadImage

Your full code will look something like:

var tex = new Texture(1,1); // note that the size is overridden
tex.LoadImage(task_.Result);
var sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(tex.width/2, tex.height/2));

You can also pack textures at runtime if that's your eventual goal. Once you get through the tex.LoadImage chunk, you should be able to work out Texture2D.PackTextures.

--Patrick

Related