2012-02-01 56 views
1

我的目标是使用Web服务上传和下载图像。我明白,为了做到这一点,图像需要转换为字节数组。但是,将字节数组转换为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; 
    } 
} 
+0

你能检查'e.ChosenPhoto.Read(PhotoBytes,0,PhotoBytes.Length)的结果;'?它应该返回读取的字节数。 – 2012-02-01 06:13:29

+0

我检查了e.ChosenPhoto.Read()的结果,并且它返回0,即使e.ChosenPhoto.Length是119264 - 我在创建字节数组时丢失了什么吗? – 2012-02-01 06:41:21

回答

4

第一次使用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); 
+0

正确,我支持Mister Goodcat,重置Position使它能够工作以获取流数据。 :) – Santhu 2012-02-01 07:03:19

0

我敢打赌,这是发生了什么(评论在线):在流中

//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

0

此:

//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); 

你开始在流中读取没有结束。

使用Seek重置流的位置。