0

當我試圖加載這樣的圖像,我得到這個錯誤指數出Bitmap.SetSourceInternal界,試圖加載

System.IndexOutOfRangeException: Index was outside the bounds of the array. 
at System.Windows.Media.Imaging.BitmapSource.SetSourceInternal(Stream streamSource) 

圖像時:

webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted); 
webClient.OpenReadAsync(new Uri("http://zomerparkfeest.nl/uploads/" + currentItem.photo), webClient); 

並在opReadAsync:

private void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) 
{ 
     if (e.Error == null && !e.Cancelled) 
     { 
      BitmapImage bitMapImage = new BitmapImage(); 
      bitMapImage.SetSource(e.Result); 
      image.Source = bitMapImage; 
      loadingImagePBar.Visibility = Visibility.Collapsed; 
      imageLocked = false; 
     } 
} 

我並不總是得到這個異常,它主要是加載了很多圖像後。什麼可能是錯的?

回答

3
Use this by Memory stream this would work fine 
    private void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) 
    { 
      if (e.Error == null && !e.Cancelled) 
      { 
       BitmapImage bitMapImage = new BitmapImage(); 
       Stream content=e.Result; 
          MemoryStream memoryStream = new MemoryStream(); 
          content.CopyTo(memoryStream); 
          memoryStream.Position = 0; 
          byte[] buffer = null; 

          if (memoryStream != null && memoryStream.Length > 0) 
          { 
           BinaryReader binaryReader = new BinaryReader(memoryStream); 
           buffer = binaryReader.ReadBytes((int)memoryStream.Length); 
          } 
          Stream stream = new MemoryStream(); 
          stream.Write(buffer, 0, buffer.Length); 
          stream.Seek(0, SeekOrigin.Begin); 
          bitMapImage.SetSource(stream); 
       image.Source = bitMapImage; 
       loadingImagePBar.Visibility = Visibility.Collapsed; 
       imageLocked = false; 
      } 
    } 
+0

謝謝!我認爲這解決了這個問題。我嘗試過一段時間後出現空指針,但似乎無法重新創建它。再次感謝! –