2010-08-06 93 views
1

System.Drawing.Image爲FromFile和ToFile提供了易於使用的方法。什麼是Silverlight BitmapImage的等價物?我正在嘗試加載並保存一個jpeg圖像作爲單元測試的一部分。該字節必須匹配正好才能通過。這是我目前的猜測:什麼是FromFile和ToFile相當於BitmapImage?

//I am not sure this is right 
    private BitmapImage GetImage(string fileName) 
    { 
     BitmapImage bitmapImage = new System.Windows.Media.Imaging.BitmapImage(); 
     using (Stream imageStreamSource = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) 
     { 
      bitmapImage.BeginInit(); 
      bitmapImage.StreamSource = imageStreamSource; 
      bitmapImage.EndInit(); 
     } 

     return bitmapImage; 
    } 

    private void SaveImage(BitmapImage bitmapImage, string file) 
    { 
     //How to do this? 
    } 

回答

1

瀏覽器中的Silverlight應用程序無法使用文件名打開文件。您需要使用提升信任的瀏覽器才能完成此操作。

Silverlight沒有內置圖像編碼,因此您無法獲取位圖的內容(順便說一下,您需要使用WriteableBitmap才能訪問原始圖像)。

你可以在Image Tools找到需要的東西。

1

從MSDN link,使用構造函數重載這需要在一個URI或

BitmapImage myBitmapImage = new BitmapImage(); 

// BitmapImage.UriSource must be in a BeginInit/EndInit block 
myBitmapImage.BeginInit(); 
myBitmapImage.UriSource = new Uri(@"C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Water Lilies.jpg"); 
myBitmapImage.DecodePixelWidth = 200; 
myBitmapImage.EndInit(); 

//set image source 
myImage.Source = myBitmapImage; 

要保存圖像到磁盤,你需要特定編碼器例如JpegBitmapEncoder

+0

什麼是DecodePixelWidth? – 2010-08-06 13:26:22

+0

來自msdn代碼片段中的註釋(第一個鏈接)「要保存重要的應用程序內存,請將圖像源的BitmapImage值的DecodePixelWidth或DecodePixelHeight設置爲所需渲染圖像的高度和寬度。如果您不這樣做這樣,應用程序將緩存圖像,就好像它被渲染爲其正常尺寸,而不僅僅是顯示的尺寸。「 – Gishu 2010-08-06 15:46:11