What's an efficient way to tell if a bitmap is entirely black?

前端 未结 12 909
清酒与你
清酒与你 2021-02-05 05:40

I\'m wondering if there\'s a super-efficient way of confirming that an Image object references an entirely black image, so every pixel within the bitmap is ARGB(255, 0, 0, 0).

12条回答
  •  清酒与你
    2021-02-05 06:21

    The first answer to this post is Awesome. I modified the code to more generically determine if the image is all one color(all black, all white, all magenta, etc...). Assuming you have a bitmap with 4 part color values ARGB, compare each color to the color in the top left if any is different then the image isn't all one color.

    private bool AllOneColor(Bitmap bmp)
    {
        // Lock the bitmap's bits.  
        Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
        BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, bmp.PixelFormat);
    
        // Get the address of the first line.
        IntPtr ptr = bmpData.Scan0;
    
        // Declare an array to hold the bytes of the bitmap.
        int bytes = bmpData.Stride * bmp.Height;
        byte[] rgbValues = new byte[bytes];
    
        // Copy the RGB values into the array.
    
        System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
    
        bool AllOneColor = true;
        for (int index = 0; index < rgbValues.Length; index++)
        {
            //compare the current A or R or G or B with the A or R or G or B at position 0,0.
            if (rgbValues[index] != rgbValues[index % 4])
            {
                AllOneColor= false;
                break;
            }
        }
        // Unlock the bits.
        bmp.UnlockBits(bmpData);
        return AllOneColor;
    }
    

提交回复
热议问题