简体   繁体   中英

Asp.net determine uploaded image black and white area %

is that possible build a asp.net application that able to determine uploaded image black and white area %?

EXAMPLE : 在此处输入图片说明

After user upload the picture ,the application will calculate the black and white area.

Output :

**White :**32%

**Black :**68%

You can use the Bitmap class. With the properties Width and Height you can calculate the total pixel count. And with the method GetPixel you can get the color of a specific pixel. To compare a known color like Color.White to an other color you can use the ToArgb method.

Image yourImage = ...

Bitmap bitmap = new Bitmap(yourImage);
int whiteColorCount = 0;
int blackColorCount = 0;
for (int i = 0; i < bitmap.Width; i++)
{
    for (int c = 0; c < bitmap.Height; c++)
    {
        int pixelHexColor = bitmap.GetPixel(i, c).ToArgb();
        if (pixelHexColor == Color.White.ToArgb())
        {
            whiteColorCount++;
        }
        else if (pixelHexColor == Color.Black.ToArgb())
        {
            blackColorCount++;
        }
    }
}

long totalPixelCount = bitmap.Width * bitmap.Height;
double whitePixelPercent = whiteColorCount / (totalPixelCount / 100.0);
double blackPixelPercent = blackColorCount / (totalPixelCount / 100.0);
double otherPixelPercent = 100.0 - whitePixelPercent - blackPixelPercent;

Yes you can convert you image to Bitmap and use this method. It return number of pixel your set color .Get number of black and white pixels and calculate how many percent is black and white.

    // Return the number of matching pixels.
private int CountPxl(Bitmap bmap, Color yourColor)
{
// Loop through the pixels.
int matches = 0;
for (int y = 0; y < bmap.Height; y++)
{
for (int x = 0; x < bmap.Width; x++)
{
if (bmap.GetPixel(x, y) == yourColor) matches++;
}
}
return matches;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM