How to save and load an image in Unity

The BinaryFormatter can handle all standard types such as int, string and bool but what happens if want to include an image in the saved data? Let’s go over how to add an image to the saved data.

First, inside the class which is holding the data change the image type to a byte array and ensure the class is serialized:

After the image has been generated it needs to be converted to a Texture2D type:

Now that the image has been converted to a texture it can be added to the class by using the EncodeToPNG:

You can now save the data as normal with BinaryFormatter:

When loading the data add it back to the class:

Lastly, to add the loaded texture back as an image on the UI create a temporary Texture2D. Use the function LoadImage to covert it from byte array and then add the texture to the UI object:

Good luck!

Unity / C# Game developer