- Home /
2D texture loaded from file different from same texture in editor
I've encountered a strange issue when loading a .png file as a texture from a local file.
I've place side by side two Image (UI) objects. both using (identical copies of) the same file. One loaded in the editor, and one loaded with code. And they look different. Specifically, the loaded with code one (right) has some artifacts that don't exist in the original file or the one preloaded into the editor.
The .png file contains transparency.
see Image (background color added to highlight artifacts, notice artifacts on the edges):
I've loaded the local .png file using the following code:
public static Sprite LoadPNGToSprite(string filepath)
{
Texture2D texture = LoadPNG(filepath);
float pixelsPerUnit = 100;
return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0), pixelsPerUnit);
}
private static Texture2D LoadPNG(string filePath)
{
Texture2D tex = null;
byte[] fileData;
if (File.Exists(filePath))
{
fileData = File.ReadAllBytes(filePath);
tex = new Texture2D(2, 2, TextureFormat.DXT5, false);
tex.LoadImage(fileData); //..this will auto-resize the texture dimensions.
}
else
{
Debug.LogError("could not find file: " + filePath);
}
return tex;
}
The import settings of the editor image are as follows (if that helps):
I'm at a loss As I have been trying to get rid of those artifacts for a few days now. If any other information is needed feel free to ask.
Answer by liortal · Aug 30, 2017 at 09:03 PM
Setting the created texture to use point filtering seems to give better results:
public static Sprite LoadPNGToSprite(string filepath)
{
Texture2D texture = LoadPNG(filepath);
texture.alphaIsTransparency = true;
texture.wrapMode = TextureWrapMode.Repeat;
texture.filterMode = FilterMode.Point;
float pixelsPerUnit = 100;
return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0), pixelsPerUnit);
}
That did it! Thanks. I still wander why the default values for those fields are different for textures imported into the editor and textures loaded by code.
I guess the sprite (and texture) importers store a bunch of other information that you are not initializing by default when you create a texture and then assign it to a sprite.
Also, the LoadImage method is very limited in itself (can only support a few texture formats, etc).
So, overall, this may be a Unity bug, or just the difference between the way Unity loads textures by this API. who knows. if it's interesting we can investigate further :)
Answer by rigward · Feb 15, 2018 at 08:42 PM
Faced the same issue some time ago, and TextureFormat.ARGB32 + setting mipmap to false solved it for me:
var texture = new Texture2D(512, 512, TextureFormat.ARGB32, false);