如何在应用程序中动态地将所选图像从图片库复制到图像文件夹?

问题描述:

我刚接触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); 

      } 
     } 
    } 

我要动态添加所选图像,以我的应用程序的图片文件夹中。这个怎么做?你能否给我提供任何可以解决上述问题的代码或链接?

这里是保存所选的图片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; 
     } 
    } 
} 

您可以参考修改后的Photo Chooser API或doco上的RTM release notes这里的一页。

How to: Create a Photo Extras Application for Windows Phone

事实上,一旦你获得流,你可以将其转换为字节和本地存储。这里是你应该在你的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