Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Texture2D Base64 En-/Decoding

Discussion in 'UGUI & TextMesh Pro' started by Diversity276, May 22, 2015.

  1. Diversity276

    Diversity276

    Joined:
    Mar 22, 2014
    Posts:
    51
    Hey there,

    does anyone has a solution to Encode a Texture2D to a string in base64-format and vise versa?


    Best regards from Germany and happy weekend.

    Diversity
     
    charmandermon likes this.
  2. Senshi

    Senshi

    Joined:
    Oct 3, 2010
    Posts:
    557
    This is untested, but I think the way to go would be something along the lines of:

    Code (csharp):
    1. //encode:
    2. Texture2D tex; //assign in Inspector, load from Resources or WebRequest or what have you
    3. byte[] imageBytes = tex.EncodeToPNG(); //encode to byte[]; you may also use EncodeToJPG()
    4. string base64Image = System.Convert.ToBase64String(imageBytes, 0, imageBytes.Length); //byte[] to base64 string (params: byte[], array offset, number of bytes to encode)
    5.  
    6. //decode:
    7. string base64Image; //again, obtain however
    8. byte[] imageBytes = System.Convert.FromBase64String(base64Image); //base64 string to byte[]
    9. Texture2D tex = new Texture2D(1, 1); //create a new texture; size doesn't matter. Set other options as needed either here, or after the next line
    10. tex.LoadImage(imageBytes); //load the byte[] into the Texture
    Hope this works, or at least helps a bit! Cheers!
     
    Diversity276 likes this.
  3. Diversity276

    Diversity276

    Joined:
    Mar 22, 2014
    Posts:
    51
    Hello Senshi,

    thank you a lot. I wish you a nice day and a wonderful weekend.

    Best regards.
     
    Senshi likes this.