Determine if Alpha Channel is Used in an Image

前端 未结 7 1926
北恋
北恋 2020-12-06 05:29

As I\'m bringing in images into my program, I want to determine if:

  1. they have an alpha-channel
  2. if that alpha-channel is used

#1

7条回答
  •  悲哀的现实
    2020-12-06 06:10

    While I know the OP is not about MagickNet, it might help s/o.

    Magick.Net provides a wrapper around Imagick lib and includes a feature to easily access channel statistics.

    Example

        public bool HasTransparentBackground(MagickImage image)
        {
            if (!image.HasAlpha) return false;
    
            var statistics = image.Statistics();
            var alphaStats = statistics.GetChannel(PixelChannel.Alpha);
    
            var alphaMax = Math.Pow(2, alphaStats.Depth);
            return alphaStats.Minimum < alphaMax * .2;
        }
    

    We first check if the image supports transparency an return if not. Then we get statistics for alpha channel and can simply check the Min property. There's also a Mean property that allows you to check "how much transparent" your image is.

    See also

    • Detect Alpha Channel with ImageMagick
    • https://github.com/dlemstra/Magick.NET

提交回复
热议问题