Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleCompare two images to find differences in VB .NET
DescriptionThis example shows how to compare two images to find differences in VB .NET.
Keywordsimage, bitmap, VB.NET, compare, difference, imagediff
CategoriesGraphics, VB.NET
 
When you select two images to compare and click the Go button, the program executes the following code. It loads the two image files into Bitmaps. It finds the smaller of the Bitmaps' widths and heights, and makes a new Bitmap of that size.

Next the program loops over the pixels in the smaller area, comparing the the images' pixels. If two corresponding pixels are equal, the program colors the result pixel white. If the two pixels are unequal, the program makes the result pixel red. When it has examined all of the pixels, the program displays the result image.

The result image highlights differences between the two input images no matter how small the differences are. If a pixel in one image has RGB values 50, 150, 200 and the corresponding pixel in the other image has RGB values 51, 150, 200, the result shows the difference plainly even though you won't be able to tell the difference with your eyes.

 
Private Sub btnGo_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnGo.Click
    Me.Cursor = Cursors.WaitCursor
    Application.DoEvents()

    ' Load the images.
    Dim bm1 As Bitmap = Image.FromFile(txtFile1.Text)
    Dim bm2 As Bitmap = Image.FromFile(txtFile2.Text)

    ' Make a difference image.
    Dim wid As Integer = Math.Min(bm1.Width, bm2.Width)
    Dim hgt As Integer = Math.Min(bm1.Height, bm2.Height)
    Dim bm3 As New Bitmap(wid, hgt)

    ' Create the difference image.
    Dim are_identical As Boolean = True
    Dim r1, g1, b1, r2, g2, b2, r3, g3, b3 As Integer
    Dim eq_color As Color = Color.White
    Dim ne_color As Color = Color.Red
    For x As Integer = 0 To wid - 1
        For y As Integer = 0 To hgt - 1
            If bm1.GetPixel(x, y).Equals(bm2.GetPixel(x, _
                y)) Then
                bm3.SetPixel(x, y, eq_color)
            Else
                bm3.SetPixel(x, y, ne_color)
                are_identical = False
            End If
        Next y
    Next x

    ' Display the result.
    picResult.Image = bm3

    Me.Cursor = Cursors.Default
    If (bm1.Width <> bm2.Width) OrElse (bm1.Height <> _
        bm2.Height) Then are_identical = False
    If are_identical Then
        MessageBox.Show("The images are identical")
    Else
        MessageBox.Show("The images are different")
    End If

    bm1.Dispose()
    bm2.Dispose()
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated