compare the lightness of the lower and upper halves of a jpeg in csharp

Here is a code snippet to compare the lightness of the lower and upper halves of a JPEG image in C# using Bitmap and Color classes:

main.cs
// Load the JPEG image
Bitmap bmp = new Bitmap("path/to/image.jpg");

// Get the height of the image
int height = bmp.Height;

// Calculate the middle line of the image
int middleLine = height / 2;

// Initialize counters for the total lightness of the upper and lower halves
int upperLightness = 0;
int lowerLightness = 0;

// Loop through all pixels in the image
for (int y = 0; y < height; y++)
{
    for (int x = 0; x < bmp.Width; x++)
    {
        // Get the color of the pixel
        Color pixel = bmp.GetPixel(x, y);

        // Calculate the lightness of the pixel
        int lightness = (int)(0.299 * pixel.R + 0.587 * pixel.G + 0.114 * pixel.B);

        // Add the lightness to the upper or lower half counter
        if (y < middleLine)
        {
            upperLightness += lightness;
        }
        else
        {
            lowerLightness += lightness;
        }
    }
}

// Calculate the average lightness of the upper and lower halves
int upperAvgLightness = upperLightness / (bmp.Width * middleLine);
int lowerAvgLightness = lowerLightness / (bmp.Width * (height - middleLine));

// Compare the average lightness of the upper and lower halves
if (upperAvgLightness > lowerAvgLightness)
{
    Console.WriteLine("The upper half of the image is brighter.");
}
else if (upperAvgLightness < lowerAvgLightness)
{
    Console.WriteLine("The lower half of the image is brighter.");
}
else
{
    Console.WriteLine("The upper and lower halves of the image have the same lightness.");
}
1503 chars
54 lines

Note that this code calculates the lightness of each pixel using a simplified formula that takes into account the human eye's sensitivity to different colors. This formula may not be accurate for all images, and you may want to use a more advanced algorithm for more precise results.

gistlibby LogSnag