我需要找到位图中每个像素的颜色,然后将像素的颜色存储在它的下面和旁边,以便稍后进行比较。然而,我在for循环中得到一个超出范围的异常错误。我不知道为什么会发生这种情况,我能做些什么来解决它?
Dim img As New Bitmap(bitmapbox.Image)
MsgBox(img.Size.ToString)
MsgBox(img.Height.ToString)
Dim pixelcolor As Color
Dim pixelcolorbelow As Color
Dim pixelcolornext As Color
Dim notstoretwice As Boolean = False
For k As Integer = 1 To img.Height - 1
For i As Integer = 1 To img.Width - 1
pixelcolor = img.GetPixel(i, k)
pixelcolorbelow = img.GetPixel(i, k + 1)
pixelcolornext = img.GetPixel(i + 1, k)
If pixelcolor.R >= pixelcolornext.R - 20 Or pixelcolor.R <= pixelcolornext.R + 20 And pixelcolor.R >= pixelcolorbelow.R - 20 And pixelcolor.R <= pixelcolorbelow.R + 20 Then
notstoretwice = True
yordinate.Add(k)
xordinate.Add(i)
If pixelcolor.G >= pixelcolornext.G - 20 And pixelcolor.G <= pixelcolornext.G + 20 And pixelcolor.R >= pixelcolorbelow.G - 20 And pixelcolor.G <= pixelcolorbelow.G + 20 And notstoretwice = False Then
notstoretwice = True
yordinate.Add(k)
xordinate.Add(i)
If pixelcolor.B >= pixelcolornext.B - 20 And pixelcolor.B <= pixelcolornext.B + 20 And pixelcolor.R >= pixelcolorbelow.B - 20 And pixelcolor.B <= pixelcolorbelow.B + 20 And notstoretwice = False Then
notstoretwice = True
yordinate.Add(k)
xordinate.Add(i)
' similar color to the selected color
End If
End If
End If
notstoretwice = False
Next
Next
pb.Height = 210
pb.Width = 110
Me.Controls.Add(pb)
Dim flag As Bitmap = New Bitmap(200, 100)
Dim flagGraphics As Graphics = Graphics.FromImage(flag)
Dim red As Integer = 0
Dim white As Integer = 11
Dim j As Integer
Dim f As Integer
For m As Integer = 0 To yordinate.Count - 1
j = yordinate(m)
f = xordinate(m)
flagGraphics.FillRectangle(Brushes.Red, j, f, 100, 100)
Next
pb.Image = flag
end sub
由于以下几行,您将得到异常:
pixelcolorbelow = img.GetPixel(i, k + 1)
pixelcolornext = img.GetPixel(i + 1, k)
这样做,当您到达各自集合的末尾时,当它去获取下一个/下一个像素时,您将获得indexoutorange。您将需要添加一个条件检查,以确保您不在结束或循环到倒数第二个高度/宽度。我个人倾向于后者:
For k As Integer = 1 To img.Height - 2
For i As Integer = 1 To img.Width - 2
' ...
Next
Next