【发布时间】:2017-04-07 02:17:14
【问题描述】:
我有这个从位图创建区域的函数:
Public Shared Function GetRegion(ByVal sender As Bitmap, ByVal transperancyKey As Color, ByVal tolerance As Integer) As Region
' Stores all the rectangles for the region.
Using path As New GraphicsPath()
' Scan the image
For x As Integer = 0 To (sender.Width - 1)
For y As Integer = 0 To (sender.Height - 1)
If Not ColorsMatch(sender.GetPixel(x, y), transperancyKey, tolerance) Then
path.AddRectangle(New Rectangle(x, y, 1, 1))
End If
Next
Next
Return New Region(path)
End Using
End Function
Public Shared Function ColorsMatch(ByVal color1 As Color, ByVal color2 As Color, ByVal tolerance As Integer) As Boolean
If (tolerance < 0) Then
tolerance = 0
End If
Return Math.Abs(color1.R - color2.R) <= tolerance AndAlso
Math.Abs(color1.G - color2.G) <= tolerance AndAlso
Math.Abs(color1.B - color2.B) <= tolerance
End Function
我想使用Bitmap.LockBits 而不是Bitmap.GetPixel 来提高性能。
目前我所拥有的是下面这个不完整的代码。尝试以与原始函数相同(有效)的方式迭代像素/颜色,我有点困惑。
Public Shared Function GetRegion(ByVal sender As Bitmap, ByVal transperancyKey As Color, ByVal tolerance As Integer) As Region
' Stores all the rectangles for the region.
Using path As New GraphicsPath()
' Lock the bitmap's bits.
Dim rect As New Rectangle(0, 0, sender.Width, sender.Height)
Dim bmpData As BitmapData = sender.LockBits(rect, ImageLockMode.ReadWrite, sender.PixelFormat)
' Get the address of the first line.
Dim ptr As IntPtr = bmpData.Scan0
' Declare an array to hold the bytes of the bitmap.
' Assume PixelFormat.Format32bppArgb (4 bytes per pixel)
Dim bytes As Integer = Math.Abs(bmpData.Stride) * sender.Height
' Note that I'm not sure whether the above is the proper calculation for that assumption.
Dim rgbValues(bytes - 1) As Byte
' Copy the RGB values into the array.
Marshal.Copy(ptr, rgbValues, 0, bytes)
' Scan the image
For x As Integer = 0 To (sender.Width - 1)
For y As Integer = 0 To (sender.Height - 1)
' ...
Next
Next
' Unlock the bits.
bmp.UnlockBits(bmpData)
Return New Region(path)
End Using
End Function
我该怎么做?
【问题讨论】:
-
您是否正在寻找简化的
GetPixel和SetPixel使用LockBits,如this post?
标签: .net vb.net image-processing bitmap pixel