'Is there a way to import a texture in a specific format?

I'm trying to load a rendered image from Blender into Unity. But I saved the image with a color depth of 16 bits per channel, and now I want to have the same accuracy inside Unity. However, when I put the texture on a material and zoom in a bit, it looks like this:

8 Bits

As far as I can tell, this is only 8 bits per channel. What fixed it for me was overriding the format in the Texture Import Settings (from the default RGBA Compressed DXT5 to RGBA64, because my image also has an alpha channel):

Settings

And now the image looks nice again:

16 Bits

However, I would like to be able to import the image at runtime. So far I've been doing it like this:

Texture2D tex = new Texture2D(0, 0);
byte[] bytes = File.ReadAllBytes(path);
tex.LoadImage(bytes);

The problem is that, according to the documentation for Texture2D.LoadImage, "PNG files are loaded into ARGB32 format" by default. And even if I set the format when creating the Texture2D, it seems to get overitten when I call LoadImage ("After LoadImage, texture size and format might change").

Is there a way to import an image in a specific format (at runtime)? Thanks in advance



Solution 1:[1]

Subclass AssetPostprocessor:

public class MyPostProcessor : AssetPostprocessor {
  public void OnPreprocessTexture() {
    if (assetPath.Contains("SomeFileName")) {
      TextureImporter textureImporter = (TextureImporter)assetImporter;
      TextureImporterPlatformSettings settings = new TextureImporterPlatformSettings();
      settings.textureCompression = TextureImporterCompression.Uncompressed;
      settings.format = TextureImporterFormat.RGBA64;
      textureImporter.SetPlatformTextureSettings(settings);
    }
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 puzzl