在位图中将红色像素更改为蓝色

时间:2018-09-02 17:21:57

标签: vb.net bitmap

我想将red像素更改为blue。图像为24位.bmp。我使用lockbits是因为它速度更快,但是代码找不到红色像素!

代码:

Dim bmp As Bitmap = New Bitmap("path")
Dim pos As Integer
Dim rect As New Rectangle(0, 0, bmp.Width, bmp.Height)
Dim bmpData As System.Drawing.Imaging.BitmapData = bmp.LockBits _
        (rect, Drawing.Imaging.ImageLockMode.ReadWrite,
        bmp.PixelFormat)
Dim ptr As IntPtr = bmpData.Scan0
Dim bytes As Integer = Math.Abs(bmpData.Stride) * bmp.Height
Dim rgbValues(bytes - 1) As Byte
Marshal.Copy(ptr, rgbValues, 0, bytes)

For y = 0 To bmp.Height - 1
    For x = 0 To bmp.Width - 1
        pos = y * bmp.Width * 3 + x * 3

        If rgbValues(pos) = 255 And rgbValues(pos + 1) = 0 And rgbValues(pos + 2) = 0 Then
            rgbValues(pos + 2) = 255
            rgbValues(pos) = 0
        End If
    Next
Next

Marshal.Copy(rgbValues, 0, ptr, bytes)
bmp.UnlockBits(bmpData)
bmp.Save("new path")

谢谢!

1 个答案:

答案 0 :(得分:3)

存储在rgbValues中的值不是不是

R G B R G B.....

但是

B G R B G R.....

所以循环中正确的代码是:

'       B                      G                            R
If rgbValues(pos) = 0 And rgbValues(pos + 1) = 0 And rgbValues(pos + 2) = 255 Then
    rgbValues(pos + 2) = 0 'R
    rgbValues(pos) = 255 'B
End If