[WindowsPhone] 關於Isolated Storage中存取讀取圖片

2013-07-29

最近在弄一些有關於Window Phone 的東西,其中我需要將圖片放到Isolated Storage 中

但是發現,網路上有許多文章做法試了卻沒用,最後在 Stack Overflow 上面有找到簡單的作法

所以就簡單包裝成兩個method 關於存取圖片至Isolated Storage

介紹一下畫面:

wp_ss_20130729_0003

按下"存入圖片至Isolated Storage"後,將整個LayoutRoot 快照存入至Isolated Storage 的sample.jpg中..
之後按下"從IsolatedStorage讀圖"後將圖片Load 回至imgMain這Image物件中.

看一下主要的兩隻methods:


/// <summary>
/// 從IsolatedStorage 中讀取圖片
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static BitmapImage ReadImageFormIsolatedStorage(string fileName)
{
    var bi = new BitmapImage();
    var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
    if (!isolatedStorage.FileExists(fileName)) return bi;
    var fs = isolatedStorage.OpenFile(fileName, FileMode.Open, FileAccess.Read);
    bi.SetSource(fs);
    fs.Close(); 
    return bi;
}
 
/// <summary>
/// 存圖片至Isolated Storage
/// </summary>
/// <param name="wb"></param>
/// <param name="fileName"></param>
/// <param name="orientation"></param>
/// <param name="quality"></param>
public static void SaveImageToIsolatedStorage(WriteableBitmap wb, string fileName, int orientation = 0, int quality = 70)
{
    var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
 
    if (isolatedStorage.FileExists(fileName))
        isolatedStorage.DeleteFile(fileName);
    var fileStream = isolatedStorage.CreateFile(fileName);
    wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, orientation, quality);
    fileStream.Close();
 
}

之後呼叫端


/// <summary>
/// 存圖按下後
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSave_Click(object sender, RoutedEventArgs e)
{
    SaveImageToIsolatedStorage(new WriteableBitmap(this.LayoutRoot, null), "sample.jpg", 100, 100);
}
 
 
/// <summary>
/// 讀取圖片按下後
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnReadImage_Click(object sender, RoutedEventArgs e)
{
    imgMain.Source = ReadImageFormIsolatedStorage("sample.jpg");
}

結果:
wp_ss_20130729_0002

很簡單吧,下方附上簡單測試的Source code.

Soruce code :


當麻許的超技八 2014 | Donma Hsu Design.