Encoding/Decoding a Picture in Unity
Objective: Break a picture into an array of bytes and reassemble it.

In yesterday’s article (https://lordkakabel.medium.com/taking-a-photo-in-unity-e6e3f5328da6), we allowed the user to take a picture with their device and we stored the path to the photo within the device. Today, we’ll use that path, break the photo into a array of bytes, and reassemble it back to a photo that we can display within our app.
First, we’ll prepare an array of bytes. If we have a path to the user’s photo, we’ll store it as a Texture2D. Then we’ll EncodeToPNG to store it in the array of bytes. We’ll store this array in our ActiveCase object, which is being maintained by the current instance of our UIManager.

Here’s an example of what our encoded image would look like if we saved it on our system:

Now we have to reverse the process to recreate the photo. We’ll create an empty Texture2D to hold the result. Then we’ll get the PhotoTaken byte array from the ActiveCase object and use the LoadImage method to assign the data to the Texture2D. Finally, we’ll assign the Texture2D to texture property of our RawImage object.

It seems like a complicated process, but it only took a few lines of code!