vb.netimagecolorsgetpixel

How do I get the color of a pixel at X,Y using vb.net


Hey I am able to set the color of image via set Pixel Property but when i put condition getPixel then no error occurs but the programme stucks

i put the code below please check it give me the solution :

    Dim b As Bitmap = New Bitmap("D:\test.bmp")

' Make Image Indexed

        Dim nii As New Bitmap(b.Width, b.Height,
System.Drawing.Imaging.PixelFormat.Format32bppPArgb)
        For y As Integer = 0 To nii.Height - 1
            For x = 0 To nii.Width - 1
                Dim cw As New Color
                cw = Color.Black
                If nii.GetPixel(x, y) = cw Then
                    nii.SetPixel(x, y, Red)
                End If

            Next
        Next
        PictureBox1.Image = FromFile("D:\test.bmp")
        PictureBox2.Image = nii

If i removed getPixel then programme works but full image color is going to be red.


Solution

  • You need to compare the ARGB values of color

    Dim cw As New Color
    cw = Color.Black
    dim curPixColor as Color = b.GetPixel(x, y)
    If curPixColor.ToArgb = cw.ToArgb Then
        nii.SetPixel(x, y, Color.Red)
    End If
    

    Or you should use the Equality Operator

    Dim cw As New Color
    cw = Color.Black
    dim curPixColor as Color = b.GetPixel(x, y)
    If Color.op_Equality(curPixColor, cw) Then
        nii.SetPixel(x, y, Color.Red)
    End If
    

    Reference:http://msdn.microsoft.com/en-us/library/system.drawing.color.op_equality(v=vs.110).aspx

    Edit: As you are getting pixel from a bmp there is no transparency supported. so your comparing color should be

    cw = Color.FromArgb(0,0,0,0)
    

    Edit2: you are reading pixed from nii you should be reading from b

    dim curPixColor as Color = b.GetPixel(x, y)
    

    full code should be something like (tested)

        Dim b As Bitmap = New Bitmap("D:\test.bmp")
    
        ' Make Image Indexed
    
        Dim nii As New Bitmap(b.Width, b.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb)
        For y As Integer = 0 To nii.Height - 1
            For x = 0 To nii.Width - 1
                Dim cw As New Color
                cw = Color.Black
                Dim curPixColor As Color = b.GetPixel(x, y)
                If curPixColor.ToArgb() = cw.ToArgb() Then
                    nii.SetPixel(x, y, Color.Red)
                Else
                    nii.SetPixel(x, y, curPixColor)
                End If
            Next
        Next
        PictureBox1.Image = Image.FromFile("D:\test.bmp")
        PictureBox2.Image = nii