Search Unity

How to read a texture from an image from local path?

Discussion in 'Scripting' started by zyonneo, Apr 29, 2020.

  1. zyonneo

    zyonneo

    Joined:
    Apr 13, 2018
    Posts:
    386
    I am looking to get the final result as texture from Application.persistent path.How to read an image from local path.WWW is obsolete can we use it now to read a file from local path.This is what I tried but getting a null pointer exception
    Code (CSharp):
    1.  IEnumerator AddImageToLibrary()
    2. {
    3.      WWW www = new WWW(Application.persistentDataPath + "/" + filename);
    4.                //Waitng for operation to complete.is this correct?
    5.                 while (!www.isDone)
    6.                 {
    7.                     Debug.Log("Not done");
    8.                     yield return null;
    9.                 }
    10.              
    11.                 if (www == null)
    12.                 {
    13.                     Debug.Log("www is null");
    14.                 }
    15.                 else
    16.                 {
    17.                    imgToTexture2d = www.texture;
    18.                 }
    19.              
    20.  
    21. }
     
    Last edited: Apr 29, 2020
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
  3. zyonneo

    zyonneo

    Joined:
    Apr 13, 2018
    Posts:
    386
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    That's a start, but it doesn't turn the bytes you get from a hard drive into a Unity-compatible Texture object.

    Fortunately this is pretty easy, and there is a LoadImage function that gets the texture from bytes.
    Code (csharp):
    1.  
    2.             var imageBytes = File.ReadAllBytes(path);
    3.             Texture2D returningTex = new Texture(2,2); //must start with a placeholder Texture object
    4.             returningTex.LoadImage(imageBytes);
    5.             returningTex.name = objectName;
    6.             return returningTex;
    7.        
     
    PraetorBlue likes this.
  5. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
  6. zyonneo

    zyonneo

    Joined:
    Apr 13, 2018
    Posts:
    386
    Why do we need to specify the height and width of texture.The image going to be read can have any size
     
  7. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    It's a placeholder, and doesn't need to be the actual dimensions of the loaded texture. In fact it should be as small as possible so as not to waste resources.
     
    zyonneo likes this.