Public Function ChangeColour(ByVal img As Bitmap, ByVal inColourR As Byte, ByVal inColourG As Byte, ByVal inColourB As Byte, ByVal outColourR As Byte, ByVal outColourG As Byte, ByVal outColourB As Byte) As Bitmap
Dim bmp As new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb)
using gr = Graphics.FromImage(bmp)
gr.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height))
End using
Dim pxf As PixelFormat = PixelFormat.Format24bppRgb
Dim rect As Rectangle = New Rectangle(0, 0, bmp.Width, bmp.Height)
Dim bmpData As BitmapData = bmp.LockBits(rect, ImageLockMode.ReadWrite, pxf)
Dim ptr As IntPtr = bmpData.Scan0
Dim numBytes As Integer = Math.Abs(bmpdata.Stride) * bmp.Height
Dim rgbValues As Byte() = New Byte(numBytes - 1) {}
Marshal.Copy(ptr, rgbValues, 0, numBytes)
Dim a As Byte = 40
For counter As Integer = 0 To rgbValues.Length - 1 Step 3
If Math.Abs(rgbValues(counter) - inColourB) < a AndAlso Math.Abs(rgbValues(counter + 1) - inColourG) < a AndAlso Math.Abs(rgbValues(counter + 2) - inColourR) < a Then
rgbValues(counter) = outColourB
rgbValues(counter + 1) = outColourG
rgbValues(counter + 2) = outColourR
End If
Next
Marshal.Copy(rgbValues, 0, ptr, numBytes)
bmp.UnlockBits(bmpData)
Return bmp
End Function
调用方法
Dim img As image = getImage("D:\问题\2.png") '原图
Dim bmp As bitmap = ChangeColour(img ,0,0,0,65,105,255) '第一个参数为传入的图片,第2~5个参数为原图颜色rgb值,默认为黑色。最后3个参数为需要替换的颜色rgb值,这里是r=65,g=105,b=255
bmp.save("D:\问题\3.png",img.RawFormat)
bmp.Dispose
bmp = ChangeColour(img ,0,0,0,255,0,0) '这里替换为红色,也就是r=255,g=0,b=0
bmp.save("D:\问题\4.png",img.RawFormat)
bmp.Dispose