How to know if the Texture2D.LoadImage succeed in loading


The user can select an image (texPath) on the PC and then the image is loaded in the script:

if (File.Exists(texPath))
    Texture2D tex = new Texture2D(2, 2);
    if (tex.LoadImage(File.ReadAllBytes(texPath)))
        GetComponent<Renderer>().material.mainTexture = tex;
        print("Texture cannot be loaded");
    print("Tex path not found at " + texPath);

If the user selects an image, it works well. Otherwise, I would like it displays “Texture cannot be loaded” if the selected file is not an image. This script seems not to works since, when the user load a file which is not a jpeg or png, the renderer texture becomes
and no error message is displayed.
So… How can I detect if the selected file is not an image (jpeg or png), so that I can display the error ?

Thanks in advance.

You could check the header of the files to see if they are pngs or jpgs (by reading the first few bytes) before loading them into a texture.

  • First 8 bytes of a png-file: 137 80 78 71 13 10 26 10 (decimal) or 89 50 4e 24 0d 0a 1a 0a (hex).
  • First 10 bytes of a jpg-file: 255 216 255 224 0 16 74 70 73 70
    (decimal) or ff d8 ff e0 00 10 4a 46 49 46 (hex)

Since it’s such a small texture, What I did was to check whether the texture was more that 8 pixels wide or high. Anything smaller than 8x8 was an error. This may or may not be a plausible solution in your case.

I know nothing about mipmap levels but I made some tests and there may be a solution. I displayed the mipmap count in both cases: when it is a png or jpeg picture, the mipmapCount returns a high value (between 10 and 12 in my tests), otherwise it returns 1.

I would like to know if an image that could be selected by the user can have only one level, so that I can test if the texture is well loaded according to the mipmapCount.

Thanks in advance.