Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Saved dynamically created textures

Discussion in 'AR' started by ayygareth, Mar 29, 2021.

  1. ayygareth

    ayygareth

    Joined:
    Mar 4, 2020
    Posts:
    3
    I'm creating a project using Vuforia and it lets people dynamically creates trackable images and then lets you create a display. These images and displays are converted into textures and applied to quads as a material.

    When the app is restarted, all the textures and displays are lost because they are not saved, how do I make it so these textures can be saved?
     
  2. metigel94

    metigel94

    Joined:
    Oct 11, 2019
    Posts:
    12
    To save the images I encoded them to .jpg (you can also use other formats such as .png) and wrote the byte array to the persistent data path.

    Code (CSharp):
    1. private void SaveTexturesToJpg(Texture2D textureToSave)
    2.     {
    3.         byte[] bytes = textureToSave.EncodeToJPG();
    4.         string filepath = Application.persistentDataPath + "/JPG_" + _nameCounter + ".jpg";
    5.         _nameCounter++;
    6.         File.WriteAllBytes(filepath, bytes);
    7.     }
    To load the file you simply have to remember the file name you gave the image and then use File.ReadAllBytes() to retrieve it.
     
    noobogami likes this.
  3. ayygareth

    ayygareth

    Joined:
    Mar 4, 2020
    Posts:
    3
    This worked great thanks! How do I go about loading the saved images as a texture now?
     
  4. metigel94

    metigel94

    Joined:
    Oct 11, 2019
    Posts:
    12
    As mentioned, you can use File.ReadAllBytes().

    I wrote this little function which returns a Texture2D component:

    Code (CSharp):
    1.     private Texture2D LoadImageFromDisk(int imageIndex)
    2.     {
    3.         Texture2D output = new Texture2D(1, 1);
    4.         string filepath = Application.persistentDataPath + "/JPG_" + imageIndex + ".jpg";
    5.         var data = File.ReadAllBytes(filepath);
    6.         output.LoadImage(data);
    7.         return output;
    8.     }
     
    noobogami likes this.