所以我有一个函数,应该将图像转换为byte()
,然后返回string
。但是,我对此有一些问题。
这是函数:
Shared Function saveSknI(ByVal tosave As Image) As String
Dim converter As New ImageConverter
Dim returnValue As String = ""
For Each imageByte As Byte() In converter.ConvertTo(tosave, GetType(Byte()))
returnValue = returnValue & Convert.ToBase64String(imageByte)
Next
Return returnValue
End Function
此函数返回一个 System.InvalidCastException
异常。
它看起来像这样:
An unhandled exception of type 'System.InvalidCastException' occurred in ***.exe
Additional information: Unable to cast object of type 'System.Byte' to type 'System.Byte[]'.
我正在使用 vb .net,但我不明白为什么这不起作用,我扫描了整个项目,只查找 byte
而不是 byte()
但它什么也没产生。
最佳答案
您的方法被声明为字符串:
Shared Function saveSknI(ByVal tosave As Image) As String
所以它不能/不会返回字节数组。此外,图像转换器不会逐字节转换。此行不会为我编译(使用 Option Strict):
For Each imageByte As Byte() In converter.ConvertTo(tosave, GetType(Byte()))
至少,我认为你的意思是 For Each imageByte As Byte
因为只有一个数组。另外,ConvertTo
返回Object
您尚未转换但正在尝试迭代。您也不需要逐字节转换为 Base64。更正并折叠:
Shared Function saveSknI(tosave As Image) As String
Dim converter As New ImageConverter
Dim bytes = DirectCast(converter.ConvertTo(tosave, GetType(Byte())), Byte())
Return Convert.ToBase64String(bytes)
End Function
这与ImageConverter
几乎完全相同。没有拳击:
Public Function ToByteArray(img As Image, imgFormat As ImageFormat) As Byte()
Dim tmpData As Byte()
Using ms As New MemoryStream()
img.Save(ms, imgFormat)
tmpData = ms.ToArray
End Using
Return tmpData
End Function
打耳光<Extension()>
并将其放入模块中,您可以将其用作扩展:
imgBytes = myImg.ToByteArray(ImageFormat.PNG)
将结果转换为 Base64:
imgB64 = Convert.ToBase64String(imgBytes)
如果您愿意,您可以创建一个 ToBase64String()
扩展并一步完成转换。
关于.net - 无法将类型 'System.Byte' 的对象转换为类型 'System.Byte[]' - vb .net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41524918/