1

Below is my code:

private double GetImageValue(Bitmap Image)
{
    double ImageValue = 0;

    for (int X = 0; X < Image.Width; X++)
    {
        for (int Y = 0; Y < Image.Height; Y++)
        {
            Color CurrentPixel = Image.GetPixel(X, Y);

            ImageValue += CurrentPixel.A + CurrentPixel.B + CurrentPixel.G + CurrentPixel.R;
        }
    }
    return ImageValue;
}

The code returns the total value of each pixel in the image. Is there a way to speed up the procedure?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83

1 Answers1

0

Something like this:

private double GetImageValue(Bitmap image)
{
double imageValue = 0;

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);
var ptr = bmpData.Scan0;
var bytes = Math.Abs(bmpData.Stride) * image.Height;
var values = new byte[bytes];

System.Runtime.InteropServices.Marshal.Copy(ptr, values, 0, bytes);

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];
    }
}
image.UnlockBits(bmpData);
return imageValue;
}
  • Welcome to Stack Overflow, and thank you for contributing an answer. Would you kindly edit your answer to to include an explanation of your code? That will help future readers better understand what is going on, and especially those members of the community who are new to the language and struggling to understand the concepts. – Jeremy Caney Nov 04 '21 at 00:04