title: Unity: Convert PNG Texture2D to byte[] array and back. Then display
body: <p>I am  writing an Android app in Unity C# which implements an sqlite database. The program tries to store pictures in the database with relevant info.</p>
  
  <p>I am trying to solve the following steps to solve a piece of this:</p>
  
  <ol>
  <li>Display a png as 'texture2d' located in the Resources folder - achieved</li>
  <li>Convert the png 'texture2d' to a byte array (to save to a db)  -???             </li>
  <li>Convert from byte array back into a 'Texture2D' and display it (PROBLEMS HERE). </li>
  </ol>
  
  <p>At step 3, when trying to convert the byte array back into a 'texture2d', something goes wrong.  A red question mark is displayed instead of the png. </p>
  
  <p>The variable 'img' is supposed to hold the texture converted back from the byte array, but trying to display 'img' just shows a big red question mark. Any help would be greatly appreciated.</p>
  
  <pre><code>public byte[] imageData;    //image byte array that wil hold texture-converted-to-png
  /******************/
  
  // Use this for initialization
  void Start () {
  
      /************************/
  
      // load texture from resource folder
      Texture2D photo = new Texture2D(355, 355);  //declare texture2d to hold pic from resources folder
      Texture2D img = new Texture2D(355, 355);    //holds texture converted back from byte array 
  
      photo = Resources.Load("eeyore") as Texture2D; //load pic from resources folder into texture2d
  
      imageData = photo.EncodeToPNG();    //Encode texture to PNG to save as Byte Array in database
      img.LoadImage(imageData);           //try to change byte array back into a texture2d to display
      img.Apply();                        //same thing happens if this is here or not
  
      GameObject rawImage = GameObject.Find("RawImage"); //Find the 'RawImage' 
      rawImage.GetComponent&lt;RawImage&gt;().texture = img;   //BIG RED ? HERE ...set a texture to the raw image ('photo' works,'img' doesnt)
  
      /*************************/
      StartSync();
  }
  </code></pre>
  
  <p>this is when i display 'photo':
  <a href="https://i.stack.imgur.com/Hv0FF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Hv0FF.png" alt="enter image description here"></a></p>
  
  <p>this is when i display 'img': 
  <a href="https://i.stack.imgur.com/dkxOO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dkxOO.png" alt="enter image description here"></a></p>