Public Class Form1
Dim bmp As Bitmap
Dim WithEvents but As Button
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
but = New Button
Me.Controls.Add(but)
but.Location = Me.ClientSize - but.Size
bmp = Bitmap.FromFile("C:\Documents and Settings\zcsor\My Documents\My Pictures\远古.jpg")
Me.BackgroundImage = bmp
End Sub
Private Sub but_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles but.Click
'下面是用了GetPixel方法,如果图片比较大,那么应该用下面的LockBits方法。
Dim x As Integer = 0, y As Integer = 0
Debug.Print(Hex(bmp.GetPixel(x, y).ToArgb).PadLeft(8, "0") & " --- " & bmp.GetPixel(x, y).ToString)
x = 1
Debug.Print(Hex(bmp.GetPixel(x, y).ToArgb).PadLeft(8, "0") & " --- " & bmp.GetPixel(x, y).ToString)
x = 2
Debug.Print(Hex(bmp.GetPixel(x, y).ToArgb).PadLeft(8, "0") & " --- " & bmp.GetPixel(x, y).ToString)
'下面使用LockBits方法,一次性获取了全部数据,所以图片比较大的时候速度会明显更快一些。
Dim b As Drawing.Imaging.BitmapData = bmp.LockBits(Rectangle.Truncate(bmp.GetBounds(GraphicsUnit.Pixel)), Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat)
Dim ptr As IntPtr = b.Scan0
Dim bytes As Integer = b.Stride * bmp.Height
Dim rgbValues(bytes - 1) As Byte
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes)
bmp.UnlockBits(b)
Debug.Print("b:" & rgbValues(0) & " " & "g:" & rgbValues(1) & " " & "r:" & rgbValues(2))
Debug.Print("b:" & rgbValues(3) & " " & "g:" & rgbValues(4) & " " & "r:" & rgbValues(5))
Debug.Print("b:" & rgbValues(6) & " " & "g:" & rgbValues(7) & " " & "r:" & rgbValues(8))
End Sub
'''Return Type: COLORREF->DWORD->unsigned int
'''hdc: HDC->HDC__*
'''x: int
'''y: int
<System.Runtime.InteropServices.DllImportAttribute("gdi32.dll", EntryPoint:="GetPixel")> _
Public Shared Function GetPixel(<System.Runtime.InteropServices.InAttribute()> ByVal hdc As Integer, ByVal x As Integer, ByVal y As Integer) As UInteger
End Function
<System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint:="GetDC")> _
Public Shared Function GetDC(<System.Runtime.InteropServices.InAttribute()> ByVal hWnd As System.IntPtr) As System.IntPtr
End Function
End Class
Dim b As New System.Drawing.Bitmap("c:\1.jpg")
Dim g As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(b)
Dim hdc As IntPtr = g.GetHdc
For x As Integer = 0 To 10
For y As Integer = 0 To 20
Debug.WriteLine(".NET" & b.GetPixel(x, y).ToArgb & " API: " & NativeMethods.GetPixel(hdc.ToInt32, x, y))
Next
Next