从picturebox捕获颜色

时间:2015-03-05 21:38:47

标签: vb.net winforms

我试图捕捉主要用于图片框中图标的颜色。此效果的一个示例是Windows任务栏(Windows 7及更高版本)如何指定应用程序图标方块的背景颜色。我只是不确定如何实现这种效果。

1 个答案:

答案 0 :(得分:0)

如果你可以将它放到System.Drawing.Bitmap中,你可以循环遍历所有像素,然后计算它们(按颜色分组)。有很多颜色,可能会有一些像素只是略有不同,它将被视为唯一。 Linq还可以帮助分组这些东西。

以下是如何操作的粗略示例。这使用已经加载了图像的WinForms PictureBox。

    ' Get a Bitmap from the PictureBox
    Dim bm As Bitmap = PictureBox1.Image
    Dim colorList As New List(Of System.Drawing.Color)

    ' One entry for every pixel (so this could get large with a large image)
    For x As Integer = 0 To bm.Width - 1
        For y As Integer = 0 To bm.Height - 1
            colorList.Add(bm.GetPixel(x, y))
        Next
    Next

    ' Get the groups of colors with the count of each color that exists and sort them in
    ' decending order so you know the first one is the most used color
    Dim groups = colorList.GroupBy(Function(value) value).OrderByDescending(Function(g) g.Count)

    ' You can loop over the groups and get their counts this way grp(0) is a color
    For Each grp In groups
        MsgBox(grp(0).Name & " - " & grp.Count)
    Next

我只是把它们按顺序排列,你可以从列表中选出第一个,因为你知道它会是最多的,等等.linq语法有点难以阅读,但非常有用。