如何使 ImageToByteArray 函数更通用?

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

我有两种方法可以将图像与字节数组相互转换,这是我从 Whosebug 上的 here 获得的。

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

当我的图像是 png 文件时,两者都可以正常工作。但是当用户选择一个 jepg 文件或 gif 我得到一个 System.Runtime.InteropServices.ExternalException: 'A generic error occurred in GDI+.'

如何使 ImageToByteArray 函数更通用?即接受更多文件格式。

Image class has a property called RawFormat,您可以尝试使用它而不是硬编码格式。

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

如果这不起作用,您需要将格式作为参数传递。

    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