Reading and Writing Bitmaps Fast in VB

GetPixel and SetPixel are very slow ways to modify and process bitmaps. Even with small bitmaps, these calls can take more than 8ms each. However reading and writing all the bytes to and from that bitmap (using the functions below) takes less than 1ms for the call.

Since writing to the array takes no time, doing this even for one pixel's change, is faster. When you are processing whole images of any size, this is the way. 

Bytes are in BGRA order, and can be converted into normal color integers by using bitconverter.

 Function imageToByte(ByRef bmpIn As Bitmap) As Byte()
        Dim rct1 As Rectangle = New Rectangle(0, 0, bmpIn.Width, bmpIn.Height)
        Dim datx As BitmapData = bmpIn.LockBits(rct1, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb)   
        Dim ptrx1 As IntPtr = datx.Scan0
        Dim byteArr((datx.Stride * bmpIn.Height) - 1) As Byte

        System.Runtime.InteropServices.Marshal.Copy(ptrx1, byteArr, 0, byteArr.GetUpperBound(0) + 1)
        bmpIn.UnlockBits(datx)
        Return byteArr

    End Function


Function byteToImage(ByRef byteArr() As Byte, ByVal picSize As Size) As Bitmap
        Dim rct1 As Rectangle = New Rectangle(0, 0, picSize.Width, picSize.Height)
        Dim pic0 As Bitmap = New Bitmap(picSize.Width, picSize.Height, PixelFormat.Format32bppArgb)
        Dim datx As BitmapData = pic0.LockBits(rct1, ImageLockMode.ReadWrite, pic0.PixelFormat)
        Dim ptrx1 As IntPtr = datx.Scan0

        System.Runtime.InteropServices.Marshal.Copy(byteArr, 0, ptrx1, byteArr.Length)
        pic0.UnlockBits(datx)
        Return (pic0)

    End Function