Turning a Photo into Byte Array- App Dev Series 13

S.J. Jason Liu
3 min readSep 15, 2021

Objective: make a taken photo into byte array that could be sent as data in Unity.

When we take a photo by using the camera from device, it can only display on the column that we asked to display the photo. If we want to send this photo out of its processing script, we need to make it into a byte array.

Convert into byte array

To get the photo from device, we need to extract the storage path that we used to capture the image in the previous article.
Before we replace the texture of Raw Image, create a string to save the storage path.

Then we can use this path to locate the photo file and set it into byte array.
To convert it, we need to create a byte array variable.

And add an if statement to check if the path is null. If it is not null, then set a Texture2D image as preparation to convert.

We have using LoatImageAtPath again from the plugin we downloaded. There are 3 parameters must noticing:

  • Path: would be the path string we just extract from device.
  • Size: which should set to the size we took the photo.
  • bool- mark as non readable: this must be “false”, otherwise you might not be able to get the photo you took.

Then use EncodeToPNG() to make it as byte array.

Now we have got a byte array of photo data, and we can send it to the script that would rebuild this photo.

Rebuild from byte array

The process we just made in the last step is making the photo into Texture2D, then we can convert it into byte array.
After sending the photo data to another script, now we need to reverse the whole process to reveal the photo again.

Let’s create a new Texture2D in the script to receive the photo data.

Then rebuild the photo from byte array by using LoadImage().

And now we can create a new Texture to make the photo can be shown on the texture of Raw Image.

Now you can use “rebuiltImage” to replace the texture of Raw Image.

And that is how to convert a photo into byte array as data.

--

--

S.J. Jason Liu

A passionate gamer whose goal is to work in video game development.