我有两种方法可以将图像与字节数组相互转换,这是我从StackOverflow上的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函数更通用?即接受更多文件格式。
答案 0 :(得分:1)
Image类具有一个名为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