Determine if a Texture2D has alpha

I’m trying to determine if a Texture2D has an alpha channel. Currently I’m just using the shotgun method:

bool hasAlpha = (texture.format == TextureFormat.Alpha8 || texture.format == TextureFormat.ARGB4444 || texture.format == TextureFormat.ARGB32 || texture.format == TextureFormat.DXT5 || texture.format == TextureFormat.PVRTC_RGBA2 || texture.format == TextureFormat.PVRTC_RGBA4 || texture.format == TextureFormat.ATC_RGBA8);

This, of course, is a bad way to do things. It’s brittle, and will break if Unity adds other format types in later releases. It’s also overkill, since the user is going to be loading the texture with a WWW call or from disk so the formats will be limited.

Is there a creative way I’m not thinking of to test if the texture has alpha or not? Perhaps some way to sample the pixels, or some property I haven’t seen?

When you load an image with the WWW class, you actually can only get the formats RGB24 (for jpegs) or ARGB32 (for pngs) as you can read over here: [WWW.texture][1].

The real question is if you just want to know the source format or if the texture actually has transparent pixels. An ARGB32 image can still be opaque.

I don’t think there’s a way to determine the exact source format with only using the Unity API. The Unity editor supports much more file formats than the runtime. As i mentioned above it all comes down to what you need this information for. If you want to figure out if an image has transparent pixels you can simply use GetPixels and iterate through all pixels and see if the alpha of any pixel is less than 1.0. If it is the image contains alpha values. If all alpha values are 1.0 the image is fully opaque so you can simply treat it as an image without alpha values, even when it actually has some.

Here’s an [extension method][2] for the Texture2D class.

public static class Texture2D_Extension
{
    public static bool HasAlpha(Color[] aColors)
    {
        for(int i = 0; i < aColors.Length; i++)
            if (aColors*.a < 1f)*

return true;
return false;
}

public static bool HasAlpha(this Texture2D aTex)
{
return HasAlpha(aTex.GetPixels());
}
}
If you have this class somewhere in your project you can simply do:
Texture2D texture;
// …
if (texture.HasAlpha())
{
// texture has transparent pixels
}
[1]: Unity - Scripting API: WWW.texture
[2]: Extension Methods - C# Programming Guide | Microsoft Learn

For those who look here: there is a way simpler solution: you can use GraphicsFormatUtility.HasAlphaChannel(texture.graphicsFormat) to easily see if there’s an alpha channel available. GraphicsFormatUtility has a LOT of other useful methods as well.

You could try using the TextureImporter class. Its an Editor Class (read about). It has a boolean method that returns if the source texture has alpha channel.

TextureImporter.DoesSourceTextureHaveAlpha();

The Unity documentation will teach more.

Good Luck!