Vb.net – How do i get the colour of a pixel in a picturebox control in visual basic 2010

vb.netvisual studio 2010

Does anyone know a way to get the colour value of a pixel in a picturebox control when it is clicked in visual basic 2010?

I have created a small paint application which im using in a kiddies game but I do not want the children to colour over the outline of the image they are colouring in. So to do so I need to check if the currently clicked pixel in the picturebox is not black.

e.g. in pseudo code

if colour not black then
    Allow pixel to be changed to current colour 
else
     Do nothing 
end if

Best Answer

This is one way you can get a pixel from PictureBox:

Private Function GetColor(pic As PictureBox, X As Integer, Y As Integer) As Color

    If pic Is Nothing Then Return Nothing

    Using tmp As New Bitmap(pic.ClientSize.Width, pic.ClientSize.Height)

        Dim r As New Rectangle(0, 0, tmp.Width, tmp.Height)

        Using g As Graphics = Graphics.FromImage(tmp)
            g.DrawImage(pic.Image, r, r, GraphicsUnit.Pixel)
        End Using

        Return tmp.GetPixel(X, Y)

    End Using

End Function

Just call it like this:

Dim col As Color = GetColor(PictureBox1, someX, someY)
Related Topic