在 Windows Phone 使用 Isolated Storage 儲存和讀取圖片
簡介
在先前寫了一個 Windows Phone App 約會大作戰,有一個功能是將電話或網址儲存成二維條碼圖片,並且會將圖片儲存在 Isolated Storage 中,在下一次跳至該 Page 時,從 Isolated Storage 讀取圖片並顯示,寫了兩個函式來對 Isolated Storage 儲存和讀取圖片,在撰寫上我習慣使用 using。
Isolated Storage 儲存和讀取圖片函式
儲存圖片至 Isolated Storage
private void SaveImageToIsolatedStorage(WriteableBitmap wbImg, string strFilePath, int iOrientation = 0, int iQuality = 85)
{
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(strFilePath))
{
myIsolatedStorage.DeleteFile(strFilePath);
}
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(strFilePath))
{
wbImg.SaveJpeg(fileStream, wbImg.PixelWidth, wbImg.PixelHeight, iOrientation, iQuality);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
讀取儲存在 Isolated Storage 的圖片
private WriteableBitmap ReadImageFormIsolated(string strFilePath)
{
WriteableBitmap wbImg = null;
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(strFilePath))
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(strFilePath, FileMode.Open, FileAccess.Read))
{
BitmapImage biImg = new BitmapImage();
biImg.SetSource(fileStream);
wbImg = new WriteableBitmap(biImg);
}
}
}
return wbImg;
}
使用方法
使用 SaveImageToIsolatedStorage
private void btnSaveQrCodeImage_Click(object sender, RoutedEventArgs e)
{
SaveImageToIsolatedStorage(writeableBitmapQrcode, "QRCode.jpg");
}
使用 ReadImageFormIsolated
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
this.imgQrCode.Source = ReadImageFormIsolated("QRCode.jpg");
}
其他相關資訊
Windows Phone Dev Center Load Isolated Storage's Image and display
微軟 MVP 當麻許的文章 [WindowsPhone] 關於Isolated Storage中存取讀取圖片