我不知道为什么我的下一个嵌套循环只经历一个循环

时间:2018-12-12 09:54:42

标签: vb.net image maze

我目前正在Visual Basic上进行迷宫游戏,我需要检索图像中所有像素的颜色。为此,我为下一个循环创建了一个嵌套-宽度为1,高度为1,当代码在两个循环中进行迭代时,它将获得每个像素的像素颜色并将其放置在二维数组中。

问题在于它仅遍历长度而不是宽度

这是我的代码:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim widthIMG As Integer
    Dim lengthIMG As Integer
    Dim pixels(438, 343) As Color
    Dim pixelsData(438, 343) As String
    Dim myBitmap As New Drawing.Bitmap(PictureBox1.Image)


    For widthIMG = 1 To myBitmap.Width
        For lengthIMG = 1 To myBitmap.Height

            pixels(widthIMG, lengthIMG) = myBitmap.GetPixel(widthIMG, lengthIMG)

            Select Case pixels(widthIMG, lengthIMG).ToString
                Case "Color [A=255, R=0, G=0, B=0]"
                    TextBox1.Text = TextBox1.Text & "Width: " & widthIMG & "Length: " & lengthIMG & "Color: " & "Black " & vbCrLf
                    pixelsData(widthIMG, lengthIMG) = "Black"
                Case "Color [A=255, R=255, G=255, B=255]"

                    TextBox1.Text = TextBox1.Text & "Width: " & widthIMG & "Length: " & lengthIMG & "Color: " & "White" & vbCrLf
                    pixelsData(widthIMG, lengthIMG) = "White"

            End Select
        Next
    Next
End Sub

2 个答案:

答案 0 :(得分:0)

您超出范围。 再次尝试此修改:

For widthIMG = 0 To myBitmap.Width - 1
    For lengthIMG = 0 To myBitmap.Height - 1

其背后的原因是数组从零开始。 当您这样做时:

For index As Integer = 1 To 5
    Debug.Write(index.ToString & ", ")
Next

您的输出将是1、2、3、4、5。

但是图像的数组从零开始,并比显示的大小小一个整数。因此,假设是342,实际上是0到341。

答案 1 :(得分:0)

您的问题在这里可能是因为有一个异常退出了您的程序。图像坐标从0开始。现在,当lengthIMG等于myBitmap.Height时,会出现错误。

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim x As Integer
    Dim y As Integer
    Dim pixels(438, 343) As Color
    Dim pixelsData(438, 343) As String
    Dim myBitmap As New Drawing.Bitmap(PictureBox1.Image)


    For x = 0 To myBitmap.Width - 1
        For y = 0 To myBitmap.Height - 1

            pixels(x, y) = myBitmap.GetPixel(x, y)

            Select Case pixels(x, y).ToString
                Case "Color [A=255, R=0, G=0, B=0]"
                    TextBox1.Text = TextBox1.Text & "X: " & x & " Y: " & y & " Color: " & "Black " & vbCrLf
                    pixelsData(x, y) = "Black"
                Case "Color [A=255, R=255, G=255, B=255]"

                    TextBox1.Text = TextBox1.Text & "X: " & x & " Y: " & y & " Color: " & "White" & vbCrLf
                    pixelsData(x, y) = "White"

            End Select
        Next
    Next
End Sub

这假定您的图像不大于438、343,因为阵列是固定的。

另外,请使用x,y作为坐标,这是标准的:)

最后一个提示,我将把您的逻辑分成较小的方法。一种加载位图并返回pixelData的方法。一种方法,它使用pixelData并为文本框返回一个字符串。这样,您可以轻松地输出到文件而不是文本框。