A basic test sample with LockBits to convert pixels of an image into gray (with well known formula), with 2 buttons (Open + Convert) and 2 PictureBoxes
I loop on pixels on Height & Width of the image, simpler to understand to change BGR value for each pixel =>
Imports System.Drawing.Imaging
Imports System.Runtime.InteropServices
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using ofd As OpenFileDialog = New OpenFileDialog()
ofd.Filter = "JPEG Files (*.jpg)|*.jpg|Bitmap Files (*.bmp)|*.bmp|PNG Files (*.png)|*.png|TIFF Files (*.tif, *.tiff)|*.tif;*.tiff|All Files (*.*)|*.*"
If ofd.ShowDialog() = DialogResult.OK Then
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
If (PictureBox1.Image IsNot Nothing) Then
PictureBox1.Image.Dispose()
End If
PictureBox1.Image = New Bitmap(ofd.FileName)
End If
End Using
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim bmp = CType(PictureBox1.Image, Bitmap)
Dim bmpData As BitmapData = bmp.LockBits(New Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb)
Dim nBytes As Integer = bmpData.Stride * bmp.Height
Dim pBytesArray As Byte() = New Byte(nBytes - 1) {}
Marshal.Copy(bmpData.Scan0, pBytesArray, 0, nBytes)
For nY As Integer = 0 To bmp.Height - 1
For nX As Integer = 0 To bmp.Width - 1
Dim nPos = nY * bmpData.Stride + nX * 4
Dim b As Byte = pBytesArray(nPos), g As Byte = pBytesArray(nPos + 1), r As Byte = pBytesArray(nPos + 2), a As Byte = pBytesArray(nPos + 3)
Dim nGray As Byte = Gray(r, g, b)
b = nGray
g = nGray
r = nGray
pBytesArray(nPos) = b
pBytesArray(nPos + 1) = g
pBytesArray(nPos + 2) = r
Next
Next
Marshal.Copy(pBytesArray, 0, bmpData.Scan0, nBytes)
bmp.UnlockBits(bmpData)
If (PictureBox2.Image IsNot Nothing) Then
PictureBox2.Image.Dispose()
End If
PictureBox2.SizeMode = PictureBoxSizeMode.StretchImage
PictureBox2.Image = bmp
End Sub
Private Function Gray(nRed As Byte, nGreen As Byte, nBlue As Byte) As Byte
Return (nRed * 299 + nGreen * 587 + nBlue * 114) / 1000
End Function
End Class