如何在IsolatedStorage中存储和获取图像?

时间:2013-09-07 22:18:49

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

我希望能够在IsolatedStorage中保存图像,然后再将其保存。

为了这个目的,我写了一个帮助器,我想从我的app中的任何地方访问它:

用于创建图片:

public static void SaveImage(Stream image, string name)
{
    try
    {
        IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();

        if (!isolatedStorage.DirectoryExists("MyImages"))
        {
            isolatedStorage.CreateDirectory("MyImages");
        }

        var filePath = Path.Combine("MyImages", name + ".jpg");

        using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Create, isolatedStorage))
        {
            StreamWriter sw = new StreamWriter(fileStream);
            sw.Write(image);
            sw.Close();
        }
    }
    catch (Exception ex)
    {
        throw new Exception("failed");
    }
}

并再次获取该图片:

public static BitmapImage Get(string name)
{
    try
    {
        IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();

        var filePath = Path.Combine("MyImages", name + ".jpg");

        using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Open, isolatedStorage))
        {
            BitmapImage image = new BitmapImage();
            image.SetSource(fileStream);
            return image;
        }
    }
    catch (Exception ex)
    {
        throw new Exception("failed");
    }
}

当我尝试设置image的来源时出现问题我收到此错误消息:

  

无法找到该组件。 (HRESULT异常:0x88982F50)

1 个答案:

答案 0 :(得分:3)

假设您在WMAppManifest.xml下拥有正确的功能,那么您需要的是:

public static void SaveImage(Stream image, string name)
{

    var bitmap = new BitmapImage();
    bitmap.SetSource(attachmentStream);
    var wb = new WriteableBitmap(bitmap);
    var temp = new MemoryStream();
    wb.SaveJpeg(temp, wb.PixelWidth, wb.PixelHeight, 0, 50);

    using (var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (!myIsolatedStorage.DirectoryExists("MyImages"))
        {
            myIsolatedStorage.CreateDirectory("MyImages");
        }

        var filePath = Path.Combine("MyImages", name + ".jpg");

        using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Create, myIsolatedStorage))
        {
            fileStream.Write(((MemoryStream)temp).ToArray(), 0, ((MemoryStream)temp).ToArray().Length);
            fileStream.Close();
        }
    }
}

这应该可以工作并将您的图像作为jpeg存储到您想要的目录中。如果没有,请确保正确使用创建目录和Path.Combine()方法。