如何将图片从MediaLibrary保存到IsolatedStorage

时间:2014-02-04 08:02:48

标签: c# windows-phone-7 windows-phone-8 isolatedstorage

我要求将MediaLibrary中“已保存图片”专辑中的5张最新图片保存到IsolatedStorage中。我不太确定完成这项任务的最佳方法。到目前为止,我正在通过MediaLibrary搜索“已保存的图片”专辑。如果专辑存在并且该专辑中存在图片,我需要拍摄以文件名“TestApp”开头的最新5张图片并将其保存到IsolatedStorage。名称将用于更新磁贴,因此每个图像的文件路径都非常具体。到目前为止我所拥有的内容如下,我不知道如何将p.GetImage()(将类型为System.IO.Stream的MediaLibrary中的图像返回)保存到具有更新文件名的IsolatedStorage

private PictureCollection _pictures = null;

    public void StoreCycleTileImages()
    {
        string _photoPath = @"\Shared\ShellContent";
        string _photoFilename = null;
        int i = 0;

        using (MediaLibrary library = new MediaLibrary())
        {
            foreach (PictureAlbum album in library.RootPictureAlbum.Albums)
            {
                if (album.Name == "Saved Pictures")
                {
                    _pictures = album.Pictures;

                    if(_pictures != null)
                    {
                        //search for the most recent pictures in the album with the correct file name
                        foreach (var p in _pictures.Reverse())
                        {
                            if (i >= 5)
                                return;

                            if (p.Name.Substring(0,7) == "TestApp")
                            {
                                i += 1;

                                using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    if (!storage.DirectoryExists(_photoPath))
                                    {
                                        storage.CreateDirectory(_photoPath);
                                    }

                                    //Update file name
                                    _photoFilename = @"" + i.ToString();

                                    if (storage.FileExists(_photoPath + @"\" + _photoFilename))
                                    {
                                        storage.DeleteFile(_photoPath + @"\" + _photoFilename);
                                    }

                                    //use p.GetImage() stream to save to IsolatedStorage with updated file name
                                    //??
                                }
                            }
                        }                            
                    }

                    break;
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

我运行了你的代码 - 你在创建文件名时错过了文件扩展名(你应该考虑它可以是jpg,png或其他图像)。我的工作代码(复制片段)如下所示:

photoFilename = @"" + i.ToString() + p.Name.Substring(p.Name.LastIndexOf('.'));
if (storage.FileExists(_photoPath + @"\" + _photoFilename))
{
    storage.DeleteFile(_photoPath + @"\" + _photoFilename);
}
using (IsolatedStorageFileStream file = storage.CreateFile(_photoPath + @"\" + _photoFilename))
    p.GetImage().CopyTo(file);