Search Unity

Texture downloaded with UnityWebRequest.GetTexture() is not readable (SOLVED)

Discussion in 'Scripting' started by Snake9, Dec 20, 2016.

  1. Snake9

    Snake9

    Joined:
    Nov 18, 2016
    Posts:
    30
    Hi,

    I want to download a texture from a distant server, and then save this texture as an image file on the device (Android/iOS).


    The code is pretty simple.

    To download the Texture, I use :

    UnityWebRequest wwwTexture = UnityWebRequest.GetTexture(textureURL);
    yield return wwwTexture.Send();
    (...)
    Texture2D imgToShare = DownloadHandlerTexture.GetContent(wwwTexture);

    (...)

    And then to save it :

    Texture2D newImg = newTexture2D(imgToShare.width,imgToShare.height,TextureFormat.RGBA32,false);
    newImg.SetPixels(imgToShare.GetPixels());
    File.WriteAllBytes(somePath, newImg.EncodeToJPG());

    However I have this exception :

    UnityException: Texture '' is not readable, the texture memory can not be accessed from scripts. You can make the texture readable in the Texture Import Settings.

    when I do the "imgToShare.GetPixels()".

    How can I make this texture readable is it is downloaded from a distant server at runtime ?

    Thank you in advance for any help. :)
     
  2. Snake9

    Snake9

    Joined:
    Nov 18, 2016
    Posts:
    30
    Okay now I know how to do that, in any case someone get the same problem, here is the solution :


    1/ Download the texture

    UnityWebRequest wwwTexture = UnityWebRequest.GetTexture(textureURL);
    yield return wwwTexture.Send();
    if(! wwwTexture.isError)
    {
    Texture2D texture = DownloadHandlerTexture.GetContent(wwwTexture);
    (...)
    }



    2/ Create a new texture and then load the downloaded bytes inside the new texture (which will be readable)

    Texture2D nexTexture = new Texture2D(texture.width, texture.height);
    newTexture.LoadImage(wwwTexture.downloadHandler.data)


    3/ Then you can use GetPixels() or EncodeToJPG() (or PNG) from the newTexture because it is readable.

    File.WriteAllBytes(somePath, newTexture.EncodeToJPG());
    Color[] colors = newTexture.GetPixels()
     
    tomekkie2 likes this.
  3. Telhurin

    Telhurin

    Joined:
    Feb 8, 2015
    Posts:
    18
    Hello!

    I hope it's not to late for this replay, but you should use GetTexture(string uri, bool nonReadable) method with second argument marked as false. But be aware! Before version 5.6 the second argument was reversed (due to the bug in code or mistake in documentation). So if u want to be able to save texture after download use:
    Lover then 5.6:
    UnityWebRequest.GetTexture(url, true)
    Unity 5.6 and higher:
    UnityWebRequest.GetTexture(url, false)
     
    Bunny83, JohnTube, xxilong and 2 others like this.
  4. Mavericks_Game

    Mavericks_Game

    Joined:
    Nov 27, 2019
    Posts:
    5
    Thank you so much!