Bitmap to byte conversion variance?
Posted on 2006-03-31
Okay, this is a tricky one... or at least tricky to explain. I have one large bitmap, and a small bitmap that I am trying to compare to a rectangle inside the larger bitmap. I have a pair of pictures that are a perfect match... I iterate through the pixels of the small bitmap and compare the GetPixel color result to that of the pixel within the larger bitmap, and it's a match.
Anyway, I asked for ideas on how to do this quickly, and Sancler had the clever idea of using a ComputeHash on the binary data. When this works, it is incredibly fast. But it doesn't always work, and I don't understand why. My code is below.
What happens is that even before I compute the hash, the byte array that results from the apparently identical bitmaps are different. In fact, they are WAY different, the byte array returned by one conversion is length 938, and the length of the other byte array is 375. From bitmaps that apparently are the same... any theories as to what could be different??
(Sancler, hoping you take a crack at this.... if this works I didn't give you enough for the original idea. :) )
Dim psmall As Bitmap = My.Resources.ComparePicA
Dim pbig As Bitmap = My.Resources.MainPic
Dim psmallcompare As Bitmap = pbig.Clone(New Rectangle(254, 189, 17, 17), pbig.PixelFormat)
MsgBox(ComparePixels(psmall, psmallcompare)) ' <---- this returns true, indicating that the subrectangle is a match
If psmall.PixelFormat = psmallcompare.PixelFormat Then
MsgBox("format is the same") ' <----- this returns true, which I think means same format
Dim ic As System.Drawing.ImageConverter = New System.Drawing.ImageConverter
Dim btImage1(1) As Byte
btImage1 = CType(ic.ConvertTo(psmall, btImage1.GetType), Byte())
Dim btImage2(1) As Byte
btImage2 = CType(ic.ConvertTo(psmallcompare, btImage2.GetType), Byte())
' problem is apparently above this point, since btImage1 and btImage2 are different byte arrays
Dim shaM As SHA256Managed = New SHA256Managed
Dim hash1 As Byte() = shaM.ComputeHash(btImage1)
Dim hash2 As Byte() = shaM.ComputeHash(btImage2)
Private Function ComparePixels(ByVal b1 As Bitmap, ByVal b2 As Bitmap) As Boolean
Dim c2 As Color
Dim c1 As Color
For x As Integer = 0 To Min(b1.Width, b2.Width) - 1
For y As Integer = 0 To Min(b1.Height, b2.Height) - 1
c1 = b1.GetPixel(x, y)
c2 = b2.GetPixel(x, y)
If c1 <> c2 Then