Search Unity

Fast way to read png as int[]

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

  1. ngyJlP

    ngyJlP

    Joined:
    Jul 4, 2018
    Posts:
    25
    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:
    38,745
    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.