首页 > 解决方案 > C#,如何获取图像内特定区域的颜色

问题描述

如何获得图像内具有 5x5px 的区域的颜色。

int xPixel = 200; int yPixel = 100;                               
Bitmap myBitmap = new Bitmap(“C:/Users/admin/Desktop/image.png");  
Color pixelColor = myBitmap.GetPixel(xPixel, yPixel, 5, 5); 
MessageBox.Show(pixelColor.Name);

此代码不起作用! 在此处输入图像描述

标签: c#imagepixels

解决方案


您可以使用这种扩展方法来获取图像区域中的主色,以防它们不完全相同

public static Color GetDominantColor(this Bitmap bitmap, int startX, int startY, int width, int height) {

    var maxWidth = bitmap.Width;
    var maxHeight = bitmap.Height;

    //TODO: validate the region being requested

    //Used for tally
    int r = 0;
    int g = 0;
    int b = 0;
    int totalPixels = 0;

    for (int x = startX; x < (startX + width); x++) {
        for (int y = startY; y < (startY + height); y++) {
            Color c = bitmap.GetPixel(x, y);

            r += Convert.ToInt32(c.R);
            g += Convert.ToInt32(c.G);
            b += Convert.ToInt32(c.B);

            totalPixels++;
        }
    }

    r /= totalPixels;
    g /= totalPixels;
    b /= totalPixels;

    Color color = Color.FromArgb(255, (byte)r, (byte)g, (byte)b);

    return color;
}

然后你可以像这样使用它

Color pixelColor = myBitmap.GetDominantColor(xPixel, yPixel, 5, 5); 

有改进的空间,比如使用Pointand Size,甚至是Rectangle

public static Color GetDominantColor(this Bitmap bitmap, Rectangle area) {
    return bitmap.GetDominantColor(area.X, area.Y, area.Width, area.Height);
}

但这应该足以开始。


推荐阅读