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

前端 未结 12 937
清酒与你
清酒与你 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:34

    I'd recommend you to lock the bitmap in the memory using the LockBits method of the System.Drawing.Bitmap type. This method returns the BitmapData type, from which you can receive a pointer to the locked memory region. Then iterate through the memory, searching for the non-zero bytes (really, faster by scanning for the Int32 or even Int64 values, depending on the platform you use). Code will look like this:

    // 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.
    Marshal.Copy(ptr, rgbValues, 0, bytes);
    
    // Scanning for non-zero bytes
    bool allBlack = true;
    for (int index = 0; index < rgbValues.Length; index++)
        if (rgbValues[index] != 0) 
        {
           allBlack = false;
           break;
        }
    // Unlock the bits.
    bmp.UnlockBits(bmpData);
    

    Consider using the unsafe code and direct memory access (using pointers) to improve performance.

提交回复
热议问题