我的目标是使用网络服务上传和下载图像。我知道为了做到这一点,需要将图像转换为字节数组。但是,在将字节数组转换为 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);
