Converting a Texture2D to a byte array and then converting it back to Texture2D in Unity can be useful for a variety of tasks, like saving a texture, transferring it over a network, or loading it from a database. Here is a step-by-step guide to achieve this, including displaying the final result on a UI or a 3D object in Unity.
Texture2D to byte[]To convert a Texture2D to a byte array, you can use the EncodeToPNG() or EncodeToJPG() methods, depending on whether you want to save the texture as a PNG or JPG. Here's an example that converts a Texture2D to a byte array using PNG encoding:
using UnityEngine; public class Texture2DConverter : MonoBehaviour { public Texture2D texture; // Assign your texture in the Unity Inspector public byte[] ConvertTextureToByteArray() { // Encode texture to PNG byte[] bytes = texture.EncodeToPNG(); return bytes; } } byte[] to Texture2DTo convert a byte array back to Texture2D, you create a new Texture2D instance and load the byte array data into it. The following code snippet demonstrates how to achieve this:
using UnityEngine; public class Texture2DConverter : MonoBehaviour { public Texture2D texture; // Assign your texture in the Unity Inspector public Texture2D ConvertByteArrayToTexture(byte[] byteArray) { // Create a new Texture2D instance Texture2D newTexture = new Texture2D(2, 2); // Size will be updated when loading data newTexture.LoadImage(byteArray); // Load byte array into the texture return newTexture; } } Texture2D in UnityYou can display a Texture2D on a UI Image component or as a material texture on a 3D object. Here are examples for both:
To display a Texture2D on a Unity UI Image component, set the sprite property:
using UnityEngine; using UnityEngine.UI; public class DisplayTextureOnUIImage : MonoBehaviour { public Image image; // Assign your UI Image in the Unity Inspector public void DisplayTexture(Texture2D texture) { // Create a sprite from the Texture2D Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f)); // Set the sprite to the Image component image.sprite = sprite; } } To display a Texture2D on a 3D object, you can assign it to a material's mainTexture property:
using UnityEngine; public class DisplayTextureOnObject : MonoBehaviour { public Renderer objectRenderer; // Assign the Renderer component of your object public void DisplayTexture(Texture2D texture) { // Assign the Texture2D to the material's main texture objectRenderer.material.mainTexture = texture; } } Suppose you have a texture, and you want to convert it to a byte array, then convert it back, and display it on a UI Image:
using UnityEngine; using UnityEngine.UI; public class TextureConversionDemo : MonoBehaviour { public Texture2D originalTexture; // Assign your texture public Image uiImage; // Assign your UI Image void Start() { Texture2DConverter converter = new Texture2DConverter(); // Convert Texture2D to byte array byte[] byteArray = converter.ConvertTextureToByteArray(); // Convert byte array back to Texture2D Texture2D newTexture = converter.ConvertByteArrayToTexture(byteArray); // Display the new texture on the UI Image DisplayTextureOnUIImage displayImage = new DisplayTextureOnUIImage { image = uiImage }; displayImage.DisplayTexture(newTexture); } } In this example, the TextureConversionDemo script converts a Texture2D to a byte array and then back to Texture2D, displaying it on a UI Image. You can also adjust the code to display it on a 3D object or perform other operations with the texture.
Converting Texture2D to Byte Array in Unity
Texture2D into a byte[] array in Unity to save or transmit the texture.using UnityEngine; public class TextureConverter : MonoBehaviour { public Texture2D texture; void Start() { // Encode texture to PNG format as byte array byte[] textureBytes = texture.EncodeToPNG(); Debug.Log("Texture converted to byte array."); } } Converting Byte Array to Texture2D in Unity
Texture2D from a byte[] array in Unity, often after retrieving data from a file or network.using UnityEngine; public class ByteArrayToTexture : MonoBehaviour { public byte[] textureBytes; void Start() { Texture2D texture = new Texture2D(2, 2); // Temporary size texture.LoadImage(textureBytes); // Convert byte array to Texture2D Debug.Log("Byte array converted to Texture2D."); } } Saving Texture2D to PNG File in Unity
Texture2D to a byte array and then saving it to a PNG file on disk.using UnityEngine; using System.IO; public class SaveTextureAsPNG : MonoBehaviour { public Texture2D texture; void Start() { byte[] pngData = texture.EncodeToPNG(); // Convert to PNG byte array File.WriteAllBytes("Assets/texture.png", pngData); // Save to file Debug.Log("Texture saved as PNG."); } } Loading PNG File into Texture2D in Unity
Texture2D.using UnityEngine; using System.IO; public class LoadTextureFromPNG : MonoBehaviour { void Start() { byte[] pngData = File.ReadAllBytes("Assets/texture.png"); // Load PNG data Texture2D texture = new Texture2D(2, 2); texture.LoadImage(pngData); // Convert to Texture2D Debug.Log("PNG file loaded into Texture2D."); } } Displaying a Reconstructed Texture2D in Unity UI
byte[] array to Texture2D and displaying it in a Unity UI element, like Image.using UnityEngine; using UnityEngine.UI; public class DisplayTextureInUI : MonoBehaviour { public Image uiImage; // Reference to the UI Image component public byte[] textureBytes; void Start() { Texture2D texture = new Texture2D(2, 2); texture.LoadImage(textureBytes); // Convert byte array to Texture2D // Assign to the Sprite of the UI Image uiImage.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero); Debug.Log("Texture displayed in UI Image."); } } Encoding and Decoding Texture2D to/from PNG
Texture2D to PNG and decoding it back to Texture2D.using UnityEngine; using System.IO; public class TextureEncodeDecode : MonoBehaviour { public Texture2D texture; void Start() { // Encode to PNG and save byte[] pngData = texture.EncodeToPNG(); File.WriteAllBytes("Assets/encoded_texture.png", pngData); // Load back from file and convert to Texture2D byte[] loadedData = File.ReadAllBytes("Assets/encoded_texture.png"); Texture2D loadedTexture = new Texture2D(2, 2); loadedTexture.LoadImage(loadedData); Debug.Log("Texture2D encoded and decoded successfully."); } } Encoding Texture2D with Different Formats
Texture2D to different formats (like JPG, PNG, etc.) and converting back.using UnityEngine; public class TextureEncodeMultipleFormats : MonoBehaviour { public Texture2D texture; void Start() { // Encode to different formats byte[] pngData = texture.EncodeToPNG(); byte[] jpgData = texture.EncodeToJPG(90); // JPG with quality 90 // Load from PNG Texture2D fromPng = new Texture2D(2, 2); fromPng.LoadImage(pngData); // Load from JPG Texture2D fromJpg = new Texture2D(2, 2); fromJpg.LoadImage(jpgData); Debug.Log("Texture2D encoded and loaded from multiple formats."); } } Debugging Conversion Issues with Texture2D
Texture2D and byte[] might fail.using UnityEngine; public class DebugTextureConversion : MonoBehaviour { public Texture2D texture; void Start() { try { // Attempt to encode to PNG byte[] pngData = texture.EncodeToPNG(); if (pngData == null || pngData.Length == 0) { throw new System.Exception("Failed to encode texture."); } // Attempt to convert back Texture2D loadedTexture = new Texture2D(2, 2); bool success = loadedTexture.LoadImage(pngData); if (!success) { throw new System.Exception("Failed to load image from byte array."); } Debug.Log("Conversion successful."); } catch (System.Exception ex) { Debug.LogError("Error during conversion: " + ex.Message); } } } Storing and Loading Texture2D in PlayerPrefs
Texture2D in PlayerPrefs as a byte[] and retrieving it later.using UnityEngine; public class StoreTextureInPlayerPrefs : MonoBehaviour { public Texture2D texture; void Start() { // Convert Texture2D to byte array and store in PlayerPrefs byte[] pngData = texture.EncodeToPNG(); PlayerPrefs.SetString("StoredTexture", System.Convert.ToBase64String(pngData)); // Base64 encoding // Retrieve and convert back to Texture2D string storedData = PlayerPrefs.GetString("StoredTexture", ""); if (!string.IsNullOrEmpty(storedData)) { byte[] textureData = System.Convert.FromBase64String(storedData); Texture2D retrievedTexture = new Texture2D(2, 2); retrievedTexture.LoadImage(textureData); Debug.Log("Texture successfully stored and loaded from PlayerPrefs."); } } } Passing Texture2D as Byte Array Between Scenes
Texture2D data between Unity scenes using byte[].using UnityEngine; using UnityEngine.SceneManagement; public class PassTextureBetweenScenes : MonoBehaviour { public static byte[] TextureData; // Static variable to hold texture data public Texture2D texture; void Start() { // Store the texture data in the static variable TextureData = texture.EncodeToPNG(); // Load the next scene SceneManager.LoadScene("NextScene"); } } public class LoadTextureInNextScene : MonoBehaviour { void Start() { if (PassTextureBetweenScenes.TextureData != null) { // Convert byte array back to Texture2D Texture2D texture = new Texture2D(2, 2); texture.LoadImage(PassTextureBetweenScenes.TextureData); Debug.Log("Texture passed and loaded in the new scene."); } } } nestedscrollview lame crystal-reports proc rest nunit binary-data android-instant-apps sass-loader setattr