Thursday, August 14, 2008

Convert image to byte array and vice versa

.NET environment provides a great set of methods to handle images and pictures. Sometimes you may need to "serialize" an image to simple array of bytes and later "deserialize" byte array back to the image.

VB.NET snippets below do the trick. Code uses MemoryStream object to convert image to bytes and back.

Imports System.Drawing.Imaging
Imports System.IO
  ''' <summary>
''' Convert a byte array to an Image
''' </summary>
''' <param name="NewImage">Image to be returned</param>
''' <param name="ByteArr">Contains bytes to be converted</param>
''' <remarks></remarks>
Public Sub Byte2Image(ByRef NewImage As Image, ByVal ByteArr() As Byte)
  '
  Dim ImageStream As MemoryStream

  Try
    If ByteArr.GetUpperBound(0) > 0 Then
      ImageStream = New MemoryStream(ByteArr)
      NewImage = Image.FromStream(ImageStream)
    Else
      NewImage = Nothing
    End If
  Catch ex As Exception
    NewImage = Nothing
  End Try

End Sub

''' <summary>
''' Convert an image to array of bytes
''' </summary>
''' <param name="NewImage">Image to be converted</param>
''' <param name="ByteArr">Returns bytes</param>
''' <remarks></remarks>
Public Sub Image2Byte(ByRef NewImage As Image, ByRef ByteArr() As Byte)
  '
  Dim ImageStream As MemoryStream

  Try
    ReDim ByteArr(0)
    If NewImage IsNot Nothing Then
      ImageStream = New MemoryStream
      NewImage.Save(ImageStream, ImageFormat.Jpeg)
      ReDim ByteArr(CInt(ImageStream.Length - 1))
      ImageStream.Position = 0
      ImageStream.Read(ByteArr, 0, CInt(ImageStream.Length))
    End If
  Catch ex As Exception
  
  End Try

End Sub
Notice that Image2Byte uses Jpeg-format. ImageFormat-class supports some other formats too, like Gif and Bmp. You may want to add required format as parameter, if needed.

1 comment:

Anonymous said...

Thank you! I used those principles in my project :)