2010-11-23 327 views
0

我剛接觸windows phone 7應用程序開發。我通過使用PhotoChooserTask類來訪問圖片庫。從圖片庫中選擇一個圖片後,我想將圖片(.jpg文件)從圖片庫添加到我的應用程序的圖像文件夾中。這個怎麼做 ?我使用下面的代碼如何在應用程序中動態地將所選圖像從圖片庫複製到圖像文件夾?

public partial class MainPage : PhoneApplicationPage 
    { 

     PhotoChooserTask photoChooserTask; 
     // Constructor 
     public MainPage() 
     { 
      InitializeComponent(); 
      photoChooserTask = new PhotoChooserTask(); 
      photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed); 
     } 

     private void button1_Click(object sender, RoutedEventArgs e) 
     { 
      photoChooserTask.Show();    
     } 

     void photoChooserTask_Completed(object sender, PhotoResult e) 
     { 
      if (e.TaskResult == TaskResult.OK) 
      { 
       BitmapImage bmp = new BitmapImage(); 
       bmp.SetSource(e.ChosenPhoto); 

      } 
     } 
    } 

我要動態添加所選圖像,以我的應用程序的圖片文件夾中。這個怎麼做?你能否給我提供任何可以解決上述問題的代碼或鏈接?

回答

4

這裏是保存所選的圖片IsolatedStorage,然後讀出來並顯示在頁面上的一個例子:

void photoChooserTask_Completed(object sender, PhotoResult e) 
{ 
    if (e.TaskResult == TaskResult.OK) 
    { 
     var contents = new byte[1024]; 

     using (var store = IsolatedStorageFile.GetUserStoreForApplication()) 
     { 
      using (var local = new IsolatedStorageFileStream("image.jpg", FileMode.Create, store)) 
      { 
       int bytes; 
       while ((bytes = e.ChosenPhoto.Read(contents, 0, contents.Length)) > 0) 
       { 
        local.Write(contents, 0, bytes); 
       } 
      } 

      // Read the saved image back out 
      var fileStream = store.OpenFile("image.jpg", FileMode.Open, FileAccess.Read); 
      var imageAsBitmap = PictureDecoder.DecodeJpeg(fileStream); 

      // Display the read image in a control on the page called 'MyImage' 
      MyImage.Source = imageAsBitmap; 
     } 
    } 
} 
0

事實上,一旦你獲得流,你可以將其轉換爲字節和本地存儲。這裏是你應該在你的Task_Completed事件處理程序是什麼:

using (MemoryStream stream = new MemoryStream()) 
{ 
    byte[] contents = new byte[1024]; 
    int bytes; 

    while ((bytes = e.ChosenPhoto.Read(contents, 0, contents.Length)) > 0) 
    { 
     stream.Write(contents, 0, bytes); 
    } 

    using (var local = new IsolatedStorageFileStream("myImage.jpg", FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication())) 
    { 
     local.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length); 
    } 
} 
+0

僅供參考。您不需要創建單獨的MemoryStream來執行此操作。另外,您的代碼不會處理由GetUserStoreForApplication()返回的IsolatedStorageFile。 – 2010-11-23 12:39:37

相關問題