I am currently making a maze game on Visual Basic and I need to retrieve the colours for all of the pixels in the image. To do this I've made a nested for next loop - 1 for width and one for height, as the code iterates through both of the loops it will get the pixel colors of each pixel and place it inside a 2 dimensional array.
The issue is it is only iterating through the length and not the width
Here my code:
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
You're out of bounds. Try again with this modification:
The reason behind this is that arrays starts at zero. When you do:
Your output will be 1, 2, 3, 4, 5.
But the array of your image starts at zero, and ends one integer less than it's shown size. So an array of, let's say 342, is really 0 to 341.
Your problem here is probably because there's an exception that exit your program. Image coordinate starts at 0. Right now, when lengthIMG is equal to myBitmap.Height, you would get an error.
This assume that your image isn't bigger than 438, 343 because your array is fixed.
Also, please use x, y for the coordinate, that is the standard :)
One last tip, I would separate your logic into smaller method. One method to load the bitmap and return a pixelsData. One method that takes a pixelsData and return a string for the textbox. That way, you could easily output to a file instead of the textbox.