Unity camera plugin save image data as bytes
Objective: convert a texture/image in Unity to byte format for serialization
In a previous article I wrote about how to setup a plugin so that the app users can take photos. Now that it is working I need to be able to save the photo and send and return the image from AWS. But before I can get to that part, I need to convert the photo in readable bytes that I can save via serialization.
To be able to convert the image that the user has taken, I need to get that image from where it is stored as the photo is taken. The path I need is already there for me, thanks to the plugin. What I need to do is convert the photo into a byte array that I can store for serialization.
The whole method above is from the plugin and I have added to it the parts I needed. In the middle I am setting the textures and the gameobject active, I am then doing the initial set up for the serialization of the photo.
I first initialise a byte array to null. If the path is not empty then I will do the following.
- Create a texture2D by assigning the photo at the given path.
- Encode the photo to the byte array
- store the imgData in the byte array in the active case
That means that I can now store the photo, the next thing to do is to reverse the operation.
- In the panel I want the photo to appear I am setting up some a new byte array and setting it to the active case byte array that was saved from the previous panel.
- Create a new Texture2D
- Use the LoadImage method to load an image into a texture, in this case I am using the byte array set up in step 1
- assigning the reconstructed image as the image texture in the panel.
This results in the photo being shown in the raw image gameobject I have set up.
All this set up is necessary as I will now need to save the active case to a .dat file and then send that file to the AWS servers. Once I have done that I can then send a request and show the returned data in the app.
If you found this helpful, don’t forget to clap and follow for more articles on game development in Unity.