Search Unity

Question Steps to send and recv image

Discussion in 'Scripting' started by zach_unity460, May 25, 2023.

  1. zach_unity460

    zach_unity460

    Joined:
    Jan 8, 2023
    Posts:
    3
    Currently, my app looks like this:

    User can upload a small icon image (or use the default one) that is associated with an object. In Unity this is displayed to the user as an `Image`.

    When they go to submit the form that will send their object details to be saved in the DB, these are the steps I'm doing to send and recv the image:

    Send:

    Code (CSharp):
    1. byte[] imgBytes = uiImg.sprite.texture.EncodeToPNG();
    2. string imgStr = Convert.ToBase64String(imgBytes);
    I then POST this via HTTP.

    When the user goes back to the page and wants to see their current objects with the icons they uploaded (or the default one if they didn't upload a custom icon), I talk to my server and get the data in JSON format. I then try to get the image and display it back to the user via:

    Recv:

    Code (CSharp):
    1. byte[] tmpBytes = Convert.FromBase64String(iconImg);
    2. Texture2D imgTexture = new Texture2D(500, 500);
    3. imgTexture.LoadImage(tmpBytes);
    4. uiImg.sprite = Sprite.Create(imgTexture, new Rect(0, 0, imgTexture.width, imgTexture.height), new Vector2(1.0f, 1.0f));
    But after this loads, the image has no sprite and is empty. It is clearly changing the default source image to empty in the editor. Screenshot 2023-05-25 at 7.53.12 AM.png
     
  2. zach_unity460

    zach_unity460

    Joined:
    Jan 8, 2023
    Posts:
    3
    Some progress:

    After changing the recv code to this, the Image now displays a question mark instead of being empty:

    Code (CSharp):
    1. byte[] tmpBytes = Convert.FromBase64String(iconImg);
    2. Texture2D imgTexture = new Texture2D(500, 500);
    3. imgTexture.LoadImage(tmpBytes);
    4. imgTexture.Apply();
    5. uiImg.sprite = Sprite.Create(imgTexture, new Rect(0, 0, imgTexture.width, imgTexture.height), new Vector2(1.0f, 1.0f));
    Screenshot 2023-05-25 at 8.11.20 AM.png
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745