Search code examples
arraysvb.netimagememorystream

How can I make the ImageToByteArray function to be more generic?


I have two methods which convert an image from and to a byte array, which I got from here on StackOverflow.

Public Function ImageToByteArray(imageIn As Image) As Byte()
    Dim ms As MemoryStream = New MemoryStream()
    imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
    Return ms.ToArray()
End Function

Public Function ByteArrayToImage(byteArrayIn As Byte()) As Image
    Dim ms As MemoryStream = new MemoryStream(byteArrayIn)
    Dim returnImage As Image = System.Drawing.Image.FromStream(ms)
    Return returnImage
End Function

Both work fine when my image is a png file. But when the user selects a jepg file or gif I get a System.Runtime.InteropServices.ExternalException: 'A generic error occurred in GDI+.'

How can I make the ImageToByteArray function to be more generic? i.e. Accept more file formats.


Solution

  • The Image class has a property called RawFormat, you can try and use it instead of hardcoding the format.

        Public Function ImageToByteArray(imageIn As Image) As Byte()
            Dim ms As MemoryStream = New MemoryStream()
            imageIn.Save(ms, imageIn.RawFormat)
            Return ms.ToArray()
        End Function
    

    If this doesn't work, you'll need to pass the format as parameter.

        Public Function ImageToByteArray(imageIn As Image, format As System.Drawing.Imaging.ImageFormat) As Byte()
            Dim ms As MemoryStream = New MemoryStream()
            imageIn.Save(ms, imageIn.RawFormat)
            Return ms.ToArray()
        End Function