Convert byte array to bitmap and vice-versa

Hi,

How do I convert a byte array to a bitmap and vice-versa in VS2005

Thanks,

Ivan



Answer this question

Convert byte array to bitmap and vice-versa

  • jwadew

    From Image to byte array:

      Me.Picture1 = New Bitmap(Me.Image)
     
    Dim
    ptr As IntPtr



      ' Lock the bitmap's bits, get a BitmapData object
      Dim rectngl As New Rectangle(0, 0, Picture1.width, Picture1.height)

    Dim bmData As System.Drawing.Imaging.BitmapData = Me.Picture1.LockBits(rectngl, _
                                              Drawing.Imaging.ImageLockMode.ReadWrite, _
                                              Drawing.Imaging.PixelFormat.Format24bppRgb)  ' <------ Pixel format

    ptr= bmData.Scan0

    Dim  bytcnt As Integer = bmpData.Stride * Picure1.height
    Dim pixels() As Byte
    Marshal.Copy(ptr, pixels, 0, bytcnt)

     

    From Byte array to image –

      Marshal.Copy(pixels, 0, ptr, bytcnt)
     
    Me.Picture1.UnlockBits(bmData)

     

    Check and recheck the Marshal.Copy(s). They are not always solid in dot net. I recommend you try this with a well characterized 16 x 16 pixel image perhaps of blacks and whites.



  • Gobi N

    A huge amount depends on the pixel format of the image.
    Create a bitmapdata object by using the LockBits method of the Bitmap Class.
    Use System.Runtime.InteropServices.Marshal.Copy to copy between array and the locked bitmap.
    Unlock the bits on the bitmap.


  • DanO84

    well you could write the contents to disk and read from that if it helps or you could write the byte array to memorystream then use an Image object to read the data from stream

  • Convert byte array to bitmap and vice-versa