How to load PNG 8 bit in runtime

Hi,

I’m currently facing a odd bug with Unity when I load PNG files with “LoadImage” method.

What I do is the following:

  1. create a Texture2D
  2. “LoadImage” file with a path
  3. Save texture2D in a file with “EncodeToPNG” and “File.WriteAllBytes” methods

Everything works well with 24b PNG files with or without alpha transparency (the original file loaded is the same as the saved texture2D).

But as soon as I try to load a 8bit PNG file with or without alpha transparency, Unity gets a weird texture and save that weird texture to PNG as well. The original file is not at all like the saved texture2D…

What I get is something semi-transparent (even when there is no transparency in original file) with purple/pink colors.

See this screenshot:
On the left, what Unity gets after loading file and/or saving texture
On the right the original file that Unity should load
alt text

What version of Unity are you using? This is a bug that I fixed recently. Try using the latest patch version.

Edit: Just checked, 5.1.2 has the fix:

Graphics: Fixed issue in Texture2D.LoadImage when loading indexed PNG images that contain an alpha channel.

If you still have problems in this version then please open a bug report:Unity QA - Bug Reporting - Unity

Karl