Bitmap data is stored in an unmanaged GDI object. Every time you call GetPixel
the system needs to access this object. You can speed it up by using LockBits
to directly access the raw image data.
private double GetImageValue(Bitmap image)
{
double imageValue = 0;
// Lock the bitmap's bits.
var rect = new Rectangle(0, 0, image.Width, image.Height);
var bmpData = image.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
// Get the address of the first line.
var ptr = bmpData.Scan0;
// Declare an array to hold the bytes of the bitmap.
var bytes = Math.Abs(bmpData.Stride) * image.Height;
var values = new byte[bytes];
// Copy the RGB values into the array.
System.Runtime.InteropServices.Marshal.Copy(ptr, values, 0, bytes);
// Add the rgb values to ImageValue
for (int y = 0; y < image.Height; y++)
{
int lineStart = y * Math.Abs(bmpData.Stride);
for (int x = 0; x < image.Width * 3; x++)
{
imageValue += values[lineStart + x];
}
}
// Unlock the bits.
image.UnlockBits(bmpData);
return imageValue;
}