Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

How to load PNG/JPG/JPEG file into Texture2D? (details)

Discussion in 'Scripting' started by rawegames, Jan 4, 2018.

  1. rawegames

    rawegames

    Joined:
    Aug 1, 2016
    Posts:
    91
    Unity Editor 5.5.4p4

    My situation:
    I'm writing an Android app that houses a picture gallery that is similar to what you see in the screenshot below. The app must load png/jpg/jpeg files on demand when they come into view, and then display them on the screen when the picture has successfully loaded. I am fine with just showing a white square while the picture is loading. Last but not least, the user must scroll through the picture gallery smoothly without any hiccups.


    My concern:
    I am currently using Texture2D.LoadImage(), and my app freezes for a split second for every image that loads. I want to remove this freeze.

    My progress:
    After doing some research, I have concluded that the only solution is to run a function (on another thread) that decodes the image. And when the thread ends, i.e. decoding is complete, call Texture2D.SetPixels().

    My attempts:
    1. When I call Texture2D.LoadImage() on another thread, it throws an exception about Texture2D.LoadImage() can only be called on the main thread.
    2. I've tried using System.Drawing to load the image, but System.Drawing does not work on Android devices.
    3. I've tried following the solution here, but after importing ImageSharp, a lot of errors appear that says minimum C# 4.0 is needed. I've also searched for other image loading libraries, but all of them uses System.Drawing.
    Thank you in advance.
    Your help is tremendously appreciated :)
     
    Last edited: Jan 4, 2018
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,140
    For #3 you can use Unity 2017.1(I think it is available in this version) or above, go into your playerSettings and change your Scripting Runtime Version to 4.6.
     
  3. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Are you loading these from disk or something? Just curious if you are sure it's the LoadImage that is the slow pause culprit?
     
  4. rawegames

    rawegames

    Joined:
    Aug 1, 2016
    Posts:
    91
    Texture2D.LoadImage() is the culprit.
    The following line of code works with zero lag:
    byte[] binaryImageData = File.ReadAllBytes(path);
    The lag occurs the moment Texture2D.LoadImage() is called.
     
    whileBreak likes this.
  5. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Okay. :)