[英]“Unspecified error” when converting a byte array into a BitmapImage
我的目標是使用網絡服務上傳和下載圖像。 我知道為了做到這一點,需要將圖像轉換為字節數組。 但是,將字節數組轉換為BitmapImage時出現“未指定錯誤”。
我已經創建了一個測試裝備,可以將圖像(從PhotoChooserTask)轉換為字節數組,然后再次返回,從而重現了我的問題。 下面列出了進行轉換的代碼,突出顯示了問題行。
任何幫助,將不勝感激!
private void PhotoChooserTaskCompleted(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
//Display the photo
BitmapImage PhotoBitmap = new BitmapImage();
PhotoBitmap.SetSource(e.ChosenPhoto);
Photo.Source = PhotoBitmap;
//Convert the photo to bytes
Byte[] PhotoBytes = new byte[e.ChosenPhoto.Length];
e.ChosenPhoto.Read(PhotoBytes, 0, PhotoBytes.Length);
//Convert the bytes back to a bitmap
BitmapImage RestoredBitmap = new BitmapImage();
MemoryStream stream = new MemoryStream(PhotoBytes);
BitmapImage image = new BitmapImage();
RestoredBitmap.SetSource(stream); //<------ I get "Unspecified error" on this line
//Display the restored photo
RestoredPhoto.Source = RestoredBitmap;
}
}
第一次將e.ChosePhoto
用作源時,將讀取流並將Position
屬性前進到末尾。 您可以在調試器中檢查PhotoBytes
數組,以查看在讀取操作之后它實際上沒有任何內容(或檢查Read
方法的返回值以確認讀取了零字節)。
您需要做的是在再次讀取之前將該Position
重置為零:
//Convert the photo to bytes
Byte[] PhotoBytes = new byte[e.ChosenPhoto.Length];
// rewind first
e.ChosenPhoto.Position = 0;
// now succeeds
e.ChosenPhoto.Read(PhotoBytes, 0, PhotoBytes.Length);
我敢打賭,這就是正在發生的事情(內聯注釋):
//Display the photo
BitmapImage PhotoBitmap = new BitmapImage();
PhotoBitmap.SetSource(e.ChosenPhoto); // This is reading from the stream
Photo.Source = PhotoBitmap;
//Convert the photo to bytes
Byte[] PhotoBytes = new byte[e.ChosenPhoto.Length];
e.ChosenPhoto.Read(PhotoBytes, 0, PhotoBytes.Length); // Fails to read the full stream
// because you already read from it
//Convert the bytes back to a bitmap
BitmapImage RestoredBitmap = new BitmapImage();
MemoryStream stream = new MemoryStream(PhotoBytes); // You're creating a stream that
// doesn't contain the image
BitmapImage image = new BitmapImage();
RestoredBitmap.SetSource(stream); // Fails because your stream is incomplete
在嘗試從流中讀取之前,請在流中Seek
為0。 並檢查Read
調用的返回值,以確保它與PhotoBytes.Length
匹配。
這個:
//Display the photo
BitmapImage PhotoBitmap = new BitmapImage();
PhotoBitmap.SetSource(e.ChosenPhoto);
Photo.Source = PhotoBitmap;
使用e.ChosenPhoto
的流,並且可能不會后退流的位置。
因此,當您執行此操作時:
Byte[] PhotoBytes = new byte[e.ChosenPhoto.Length];
e.ChosenPhoto.Read(PhotoBytes, 0, PhotoBytes.Length);
您從流的結尾開始,什么也沒讀。
使用搜索來重置流的位置。
您是否查看了我已經做過的其他帖子? 我從中獲得了很好的評價。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.