Loading data from a .png into a Texture2D object yields the wrong color data

As the title explains I am trying to procedurally create Texture2D objects in unity from .png files. However, when I draw the Texture2D object to my scene the color data is incorrect when compared to the source file. I’m not sure if this is unity’s Texture2D.LoadImage messing up or if I’m not understanding File.ReadAllBytes() correct.

How the png looks

How the Texture2D looks in Unity

This is my function that takes the path to the png and creates a Texture2D object

/// <summary>
/// Creates a Unity Texture2D object with the data from a .png picture file
/// </summary>
/// <param name="res"> resolution of the picture </param>
/// <param name="path"> path to the picture to use </param>
/// <returns> Texture2D object with pixel data </returns>
private Texture2D CreateTexture(int res, string path)
{
    var tex = new Texture2D(res, res);
    tex.filterMode = FilterMode.Point;  // Thought maybe this would help 
    var bytes = File.ReadAllBytes(path);
    tex.LoadImage(bytes);
    return tex;
}

There are several things unclear. Is the “error” you talk about those white patches that exist in Unity but not in your original? Because the colors looks fine to me, I’ve checked them all and they match. Next are those “white patches” the actual pixels of your image? Both of your images are rather large. So it’s unclear if you just scaled them up. Assuming they are pixels it means your image has a non power of two size which could cause issues on some devices, but not necessary. The usage of your “res” parameter is pointless since the size of the texture before the LoadImage call is irrelevant since the texture is replaced so the size will change anyways to the size of the texture loaded. For performance it’s better to iust create a 1x1 texture.

Have you checked your source PNG file in other applications (if on windows, open it in MS Paint or some other image viewer). It would help if you would provide the actual source png file so we can have a look at it.

Finally we don’t know how you display that texture inside Unity and which shader is used.