如何在打开应用程序之前将图像文件存储在隔离存储中
本文关键字:存储 文件 图像 隔离 应用程序 | 更新日期: 2023-09-27 18:21:05
我想在应用程序开始执行之前将jpeg文件存储在隔离存储中。我已经在应用程序的第一页中将这些图像设置为图像控件的源(通过数据绑定)。但每次执行应用程序时,我都会得到一个孤立的存储异常。我已经在App.xaml.cs的application_launchin()函数中插入了以下代码。我也尝试将其插入App.xamm.cs的构造函数中,但仍然出现了异常。我在第一页使用了数据绑定,转换器中出现异常。请帮助
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
myIsolatedStorage.CreateDirectory("DirForMyImage");
bi = new BitmapImage(new Uri("/images/myImage.jpg", UriKind.Relative));
bi.ImageOpened += new EventHandler<RoutedEventArgs>(imageTest_ImageOpened);}
这是我保存图像的事件处理程序
void imageTest_ImageOpened(object sender, RoutedEventArgs e)
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile("Certificate/Birth Certificate.jpg"))
{
WriteableBitmap wb = new WriteableBitmap(bi);
wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
}}}
转换器的功能如下。
public class IsoImageConverter : IValueConverter
{
WriteableBitmap bitmap = new WriteableBitmap(200, 200);
//Convert Data to Image when Loading Data
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
String path = (String)value;
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(path, FileMode.Open, FileAccess.Read))//=====>exception occurs here
{
// Decode the JPEG stream.
bitmap = new WriteableBitmap(400,400);
bitmap.LoadJpeg(fileStream);
fileStream.Dispose();
}
}
return bitmap;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
我建议将此逻辑放在应用程序启动事件的处理程序中。当您通过Visual Studio模板创建新的WP7应用程序时,您将在App.xaml.cs
文件中找到以下方法:
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
当Launching
事件触发时,会调用此方法。