Search code examples
c#imageunity-game-engineloadtexture2d

Unity Texture2D loadImage exact values


Why with Unity when I load an external 1024x1024 RGBA32 .png (saved via either PaintXP or Gimp) with a blob of (64,64,64) pixels in the centre does the Debug.Log line at the bottom return incorrect values? - The closest I can get is with an uncompressed .png (from Gimp) with values like (65,66,65), but with a standard image they seem to come back as (56,56,56).

    Texture2D tex = null;
    byte[] fileData;
    if (File.Exists(mapPath + "/map.png"))
    {
        fileData = File.ReadAllBytes(mapPath + "/map.png");
        tex = new Texture2D(size, size, TextureFormat.RGBA32, false);
        tex.anisoLevel = 0;
        tex.Compress(false);
        tex.filterMode = FilterMode.Point;
        tex.LoadImage(fileData); // Auto-resize the texture dimensions
        Color32[] pixelsRaw = tex.GetPixels32(0);
        Color32[,] pixels = new Color32[size, size];
        for (int j = 0; j < size - 1; j++)
        {
            for (int i = 0; i < size - 1; i++)
            {
                pixels[i, j] = pixelsRaw[(j * tex.height) + i];
            }
        }
        Debug.Log(pixels[512, 512]);
    }

This was all in an attempt to read a tile-based level from a .png image. But with the returned values being so inaccurate, I can't seem to find a way to make this possible. (I've done this loads of times with Java.awt/LWJGL and it works fine there, why not Unity?)

To clarify, this image is being loaded from outside the Unity project, so there is no way to manually set the compression/format settings via the editor.


Solution

  • There are a couple of problems: compression and gamma correction.

    1. When you call Compress on your Texture2D it will compress your texture. The bool parameter only tells it to do a low quality or high quality compression. So just remove the line: tex.Compress(false);

    2. The PNG has gamma information. Gimp has an option when you export to png to save gamma or not. So open your image in Gimp and export it with the "Save Gamma" option unchecked.

    Alternatively I was able to get the same result by removing the gAMA and sRGB attributes from the png with TweakPNG.