![](/img/trans.png)
[英]Error! unable to cast object of type 'system.object ' to type 'system.byte[]'
[英]Unable to cast object of type 'System.Byte' to type 'System.Byte[]' - vb .net
所以我有一個函數,它應該將圖像轉換為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
異常。 它看起來像這樣:
***.exe 中發生類型為“System.InvalidCastException”的未處理異常
附加信息:無法將“System.Byte”類型的對象轉換為“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()
擴展並在其中一步完成轉換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.