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. We are updating our Terms of Service for all Unity subscription plans, effective October 13, 2022, to create a more streamlined, user-friendly set of terms. Please review them here: unity.com/legal/terms-of-service.
    Dismiss Notice
  3. Have a look at our Games Focus blog post series which will show what Unity is doing for all game developers – now, next year, and in the future.
    Dismiss Notice
  4. Join us on Thursday, September 29, for a day with Unity's SRP teams here on the forum or on Reddit, and discuss topics around URP, HDRP, and the Scriptable Render Pipeline in general.
    Dismiss Notice

Fast way to read png as int[]

Discussion in 'Scripting' started by unity_ngyJlPjCCQykxg, Aug 8, 2022.

  1. unity_ngyJlPjCCQykxg

    unity_ngyJlPjCCQykxg

    Joined:
    Jul 4, 2018
    Posts:
    15
    I'm looking for the fastest way to treat a png file as an array of Int32 instead of Color32. The array is to be looped over only once and contains > 30 millions elements.

    Code (CSharp):
    1. int[] intmapArray = Resources.Load<Texture2D>("colormap").GetRawTextureData<int>().ToArray();
    2.  
    3. Color32 IntToColor(int colInt) => new((byte)colInt, (byte)(colInt >> 8), (byte)(colInt >> 16), (byte)(colInt >> 24))
    Currently I'm using I'm using GetRawTextureData<int>() to get a NativeArray and then convert it to an int[] which is much faster than any byte[] or Color32[] alternative I've tried.

    But slower than if I can get the BinaryFormatter to treat the png directly as an int[], or some equally-efficient method. Thanks in advance!
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    28,162
    I wonder if there's some kind of tricks you could with the GCHandle stuff... like pinning it and pointing at it with a System.IntPtr, then shovel it back into an int[] array?

    https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.gchandle?view=net-6.0

    Not sure of the performance of all of that though.

    I did use an OpenCV package off the asset store back in 2014 but it was a for-pay assset and I don't have access to it anymore anyway. Its generic type was what they called a
    Mat
    , basically an any-shaped vector, and they had rapid ways of getting Textures in and out of Mats.
     
unityunity