2

我有一個帶有指定URL的Web圖像,它可以在瀏覽器中瀏覽。從WP8中的網址加載圖片

我試圖從網頁URL取得它,當程序進入bitmapImage.SetSource(ms);我得到一個異常「

ex = {System.Exception: The component cannot be found. (Exception from HRESULT: 0x88982F50) 
    at MS.Internal.XcpImports.CheckHResult(UInt32 hr) 
    at MS.Internal.XcpImports.BitmapSource_SetSource(BitmapSource bitmapSource, CValue& byteStream) 
    at System.Wi... 

」 我沒有搜查計算器其他問題...但沒有這方面的幫助。任何人都可以幫助我?

字節數組確實有數據,在運行時調試時,它返回imageByteArray = {byte [1227]};我的選擇是在將字節數組轉換爲BitmapImage時發生異常。

在HttpClient的包裝類

public static async Task<Byte[]> GetWebImageByImageName(string ImageName) 
     { 
      //Uri imageServerUril = new Uri(ImageName); 

      var requestMessage = new HttpRequestMessage(HttpMethod.Get, ImageName); 
     var responseMessage = await client.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead); 

     var responseData = await responseMessage.Content.ReadAsByteArrayAsync(); 
     return responseData; 

     } 
在視圖模型

private async void ReadArticleList(int pageNumber) 
     { 
       string webURL = "http://....."; // the web URL is no problem 
       try 
       { 
        byte[] imageByteArray = await CollectionHttpClient.GetWebImageByImageName(webURL);// 


       //Convert it to BitmapImage    
        using (MemoryStream ms = new MemoryStream(imageByteArray)) 
        { 
         BitmapImage bitmapImage = new BitmapImage(); 
         bitmapImage.CreateOptions = BitmapCreateOptions.DelayCreation; 
         bitmapImage.SetSource(ms); // the exception got here 
         item.BitImage = bitmapImage; 
        } 



       IsLoading = false; 


      } 
      catch(Exception ex) 
      { 
       if (ex.HResult == -2146233088 && ex.Message.Equals("Response status code does not indicate success: 404().")) 
       { 
        MessageBox.Show("The network is not set right. Internet cannot be accessed."); 
       } 
       else 
       { 
        MessageBox.Show("sorry, no data."); 
       } 

       IsLoading = false; 
      } 

     } 

*爲詳細*

  1. BitImage是的BitmapImage的實例;
  2. item.BitImage:產品文章
  3. 圖像格式的實例JPEG

文章模型是在下面:

public class Article : INotifyPropertyChanged 
    { 
     private long _Id; 
     public long ID 
     { 
      get { return _Id; } 
      set 
      { 
       if (_Id != value) 
       { 
        _Id = value; 
        NotifyPropertyChanged("ID"); 
       } 
      } 
     } 


     private string _subject; 
     public string Subject 
     { 
      get 
      { 
       return _subject; 
      } 
      set 
      { 
       if (_subject != value) 
       { 
        _subject = value; 
        NotifyPropertyChanged("Subject"); 
       } 
      } 
     } 

     private string _words; 
     public string Words 
     { 
      get 
      { 
       return _words; 
      } 
      set 
      { 
       if (_words != value) 
       { 
        _words = value; 
        NotifyPropertyChanged("Words"); 
       } 
      } 
     } 

     private DateTime _publishDate; 
     public DateTime PublishDate 
     { 
      get 
      { return _publishDate; } 
      set 
      { 
       if (_publishDate != value) 
       { 
        _publishDate = value; 
        NotifyPropertyChanged("PublishDate"); 
       } 
      } 
     } 

     public List<string> ImagePathList = new List<string>(); 

     public BitmapImage BitImage = new BitmapImage(); 

     private string _firstImage; 
     public string FirstImage 
     { 
      get 
      { 
       return _firstImage; 
      } 
      set 
      { 
       if (_firstImage != value) 
       { 
        _firstImage = value; 
        NotifyPropertyChanged(); 
       } 
      } 
     } 

     public event PropertyChangedEventHandler PropertyChanged; 
     private void NotifyPropertyChanged([CallerMemberName] string propertyName = "") 
     { 
      PropertyChangedEventHandler handler = PropertyChanged; 
      if (null != handler) 
      { 
       handler(this, new PropertyChangedEventArgs(propertyName)); 
      } 
     } 
    } 
+1

第一個問題,你爲什麼只是不要設置Image.Source =「http://...image.jpg」?你有沒有嘗試下載圖像作爲流而不是字節[]? –

+0

我測試了你的代碼,它與我使用的testimages(包括jpegs)一起工作。您可以在設置URI時顯示圖像嗎?你仍然可以做的一件事是使用HttpClient的GetByteArrayAsync方法,因爲這將消除轉換回復的需要。 – Mark

+0

@Martin Suchan,我不確定,Image.Source是異步或同步,所以我決定將自己的Web圖像異步處理;我試圖下載圖像作爲字節[],然後我需要將其轉換爲BitmapImage,流只是在字節[]和BitmapImage之間的溫度。 – max

回答

1

@馬克,你是正確的,這符合你的建議。

我認爲這個問題是,如果我下面使用的代碼,我得到的字節數組是字節[1227]

var requestMessage = new HttpRequestMessage(HttpMethod.Get, ImageName); 
     var responseMessage = await client.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead); 

     var responseData = await responseMessage.Content.ReadAsByteArrayAsync(); 
     return responseData; 

和如果我使用var byteArray = await client.GetByteArrayAsync(ImageName);字節數組的大小是字節[5996]

我不知道爲什麼會發生這種情況,但Mark的解決方案很有用。

所有我的代碼如下:

在MVVM模式

 // get image from URL, ImageName is an absolute Url 
     public static async Task<BitmapImage> GetWebImageByImageName(string ImageName) 
     { 
      //Uri imageServerUril = new Uri(ImageName); 

      var byteArray = await client.GetByteArrayAsync(ImageName); 


      //Convert byte array to BitmapImage  
      BitmapImage bitmapImage; 
      using (MemoryStream ms = new MemoryStream(byteArray)) 
      { 
       bitmapImage = new BitmapImage(); 
       bitmapImage.SetSource(ms); 
      } 

      return bitmapImage; 


     } 
在視圖模型

public void LoadPage(int pageNumber) 
     { 
      if (pageNumber == 1) 
      { 
       this.ArticleCollection.Clear(); 
      } 

      IsLoading = true; 
      ReadArticleList(pageNumber); 

     } 

private async void ReadArticleList(int pageNumber) 
     { 
      try 
      { 

       List<Article> articleList = new List<Article>(); 
       articleList = await CollectionHttpClient.GetArticlesByPageAsync(pageNumber); 

       foreach (var item in articleList) 
       { 

        item.BitImage = await CollectionHttpClient.GetWebImageByImageName(item.ImagePathList[0]); 


        this.ArticleCollection.Add(item); 

       } 

       IsLoading = false; 


      } 
      catch(Exception ex) 
      { 
       if (ex.HResult == -2146233088 && ex.Message.Equals("Response status code does not indicate success: 404().")) 
       { 
        MessageBox.Show("The network is not set right. Internet cannot be accessed."); 
       } 
       else 
       { 
        MessageBox.Show("sorry, no data."); 
       } 

       IsLoading = false; 
      } 

     } 

型號

是:

public class Article : INotifyPropertyChanged 
    { 
     private long _Id; 
     public long ID 
     { 
      get { return _Id; } 
      set 
      { 
       if (_Id != value) 
       { 
        _Id = value; 
        NotifyPropertyChanged("ID"); 
       } 
      } 
     } 


     private string _subject; 
     public string Subject 
     { 
      get 
      { 
       return _subject; 
      } 
      set 
      { 
       if (_subject != value) 
       { 
        _subject = value; 
        NotifyPropertyChanged("Subject"); 
       } 
      } 
     } 

     private string _words; 
     public string Words 
     { 
      get 
      { 
       return _words; 
      } 
      set 
      { 
       if (_words != value) 
       { 
        _words = value; 
        NotifyPropertyChanged("Words"); 
       } 
      } 
     } 

     private DateTime _publishDate; 
     public DateTime PublishDate 
     { 
      get 
      { return _publishDate; } 
      set 
      { 
       if (_publishDate != value) 
       { 
        _publishDate = value; 
        NotifyPropertyChanged("PublishDate"); 
       } 
      } 
     } 

     private ObservableCollection<string> _imagePathList = new ObservableCollection<string>(); 
     public ObservableCollection<string> ImagePathList 
     { 
      get { return this._imagePathList; } 
      set 
      { 
       if (this._imagePathList != value) 
       { 
        this._imagePathList = value; 
        // I'm going to assume you have the NotifyPropertyChanged 
        // method defined on the view-model 
        this.NotifyPropertyChanged(); 
       } 
      } 
     } 

     BitmapImage _image; 
     public BitmapImage BitImage 
     { 
      get 
      { 
       return _image; 
      } 
      set 
      { 
       if (ImagePathList.Any()) 
       { 
        value = new BitmapImage(new Uri(ImagePathList.FirstOrDefault(), UriKind.RelativeOrAbsolute)); 
        _image = value; 
       } 
      } 
     } 

     private Uri _firstImage; 
     public Uri FirstImage 
     { 
      get 
      { 
       return _firstImage; 
      } 
      set 
      { 
       if (_firstImage != value) 
       { 
        _firstImage = value; 
        NotifyPropertyChanged("FirstImage"); 
       } 
      } 
     } 


     public event PropertyChangedEventHandler PropertyChanged; 
     private void NotifyPropertyChanged([CallerMemberName] string propertyName = "") 
     { 
      PropertyChangedEventHandler handler = PropertyChanged; 
      if (null != handler) 
      { 
       handler(this, new PropertyChangedEventArgs(propertyName)); 
      } 
     } 
    } 
0

首先,如果你有,你可以給鏈接的url綁定參數,它會自動顯示圖像,或者如果你想下載圖像並保存它&然後顯示它,所以這裏是代碼字節圖像&圖像到字節。

{ 
     BitmapImage image = new BitmapImage(); 
     MemoryStream ms = new MemoryStream(); 
     WriteableBitmap wb = new WriteableBitmap(image); 
     wb.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100); 
     imageBytes = ms.ToArray(); 
    } 

使用這個來保存圖像,因爲我使用它我的代碼。

+0

你在哪裏找到了FromStream方法,你確定它在WP8中? – max

+0

我的錯誤更新了代碼看這個。 – Dragon

2

如果你只是想不保存它顯示從遠程服務器的圖像,請執行以下操作:

imageControl1.Source = new BitmapImage(new Uri("http://delisle.saskatooncatholic.ca/sites/delisle.saskatooncatholic.ca/files/sample-1.jpg", UriKind.Absolute)); 

如果你想保存圖像IsolatedStorage你可以做到以下幾點:

WebClient webClientImg = new WebClient(); 
webClientImg.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted); 
webClientImg.OpenReadAsync(new Uri("http://delisle.saskatooncatholic.ca/sites/delisle.saskatooncatholic.ca/files/sample-1.jpg", UriKind.Absolute)); 

    void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) 
    { 
     isSpaceAvailable = IsSpaceIsAvailable(e.Result.Length); 
     if (isSpaceAvailable) 
     { 
      SaveToJpeg(e.Result); 
     } 
     else 
     { 
      MessageBox.Show("You are running low on storage space on your phone. Hence the image will be loaded from the internet and not saved on the phone.", "Warning", MessageBoxButton.OK); 
     } 
    } 

函數檢查IsolatedStorage空間是否可用,否則它不會下載圖像。

private bool IsSpaceIsAvailable(long spaceReq) 
    { 
     using (var store = IsolatedStorageFile.GetUserStoreForApplication()) 
     { 
      long spaceAvail = store.AvailableFreeSpace; 
      if (spaceReq > spaceAvail) 
      { 
       return false; 
      } 
      return true; 
     } 
    } 

如果空間是可用的,使用下面的函數作爲圖像保存到IsolatedStorage:

private void SaveToJpeg(Stream stream) 
    { 
     using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication()) 
     { 
      using (IsolatedStorageFileStream isostream = iso.CreateFile("image1.jpg")) 
      { 
       BitmapImage bitmap = new BitmapImage(); 
       bitmap.SetSource(stream); 
       WriteableBitmap wb = new WriteableBitmap(bitmap); 
       // Encode WriteableBitmap object to a JPEG stream. 
       Extensions.SaveJpeg(wb, isostream, wb.PixelWidth, wb.PixelHeight, 0, 85); 
       isostream.Close(); 

       LoadImageFromIsolatedStorage(); //Load recently saved image into the image control 
      } 
     } 
    } 

負載從IsolatedStorage在圖像控制的圖像:

private void LoadImageFromIsolatedStorage() 
    { 
     byte[] data; 

     try 
     { 
      using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) 
      { 
       using (IsolatedStorageFileStream isfs = isf.OpenFile("image1.jpg", FileMode.Open, FileAccess.Read)) 
       { 
        data = new byte[isfs.Length]; 
        isfs.Read(data, 0, data.Length); 
        isfs.Close(); 
       } 
      } 
      MemoryStream ms = new MemoryStream(data); 
      BitmapImage bi = new BitmapImage(); 
      bi.SetSource(ms); 
      imageControl1.Source = bi; 
     } 
     catch 
     { 
     } 
    } 

圖像拍攝隨機從谷歌搜索。圖像的信用謊言的主人。

希望這會有所幫助。 :)