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

问题描述 投票:1回答:1

我想将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")

谢谢!

vb.net bitmap
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.