当我尝试将一些图像保存到IsolatedStorage时,会发生Out of Memory异常。如果图像计数超过20,则会发生此错误。我正在下载所有这些图像并将它们保存在隔离存储中的临时文件夹中。当我尝试将这些图像从临时文件夹保存到隔离存储中名为myImages的文件夹时,会发生此错误。从temp中读取每张照片并逐个写入myImages。当大约20或25张照片保存到myImages时,会出现此错误。图片的平均大小为350-400 KB。如何避免此错误?
我的代码是:
private void SaveImages(int imageCount)
{
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
BitmapImage bitmap;
string tempfoldername = "Temp";
string tempfilename = string.Empty;
string folderName = "myImages";
string imageName = string.Empty;
for (int i = 0; i < imageCount; i++)
{
tempfilename = tempfoldername + "\\" + (i + 1) + ".jpg";
bitmap = GetImage(tempfoldername, tempfilename);
imageName = folderName + "\\" + (i + 1) + ".jpg";
SaveImage(bitmap, imageName, folderName);
if (isf.FileExists(imageName))
isf.DeleteFile(imageName);
bitmap = null;
}
}
private BitmapImage GetImage(string foldername, string imageName)
{
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isfs;
BitmapImage bi = new BitmapImage();
MemoryStream ms = new MemoryStream();
byte[] data;
int FileSize = 0;
if (isf.DirectoryExists(foldername))
{
isfs = isf.OpenFile(imageName, FileMode.Open, FileAccess.Read);
data = new byte[isfs.Length];
isfs.Read(data, 0, data.Length);
ms.Write(data, 0, data.Length);
FileSize = data.Length;
isfs.Close();
isfs.Dispose();
bi.SetSource(ms);
ms.Dispose();
ms.Close();
return bi;
}
return null;
}
private void SaveImage(BitmapImage bitmap, string imageName, string folderName)
{
int orientation = 0;
int quality = 100;
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isf.DirectoryExists(folderName))
isf.CreateDirectory(folderName);
if (isf.FileExists(imageName))
isf.DeleteFile(imageName);
Stream fileStream = isf.CreateFile(imageName);
WriteableBitmap wb = new WriteableBitmap(bi);
wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, orientation, quality);
fileStream.Close();
}
}
我该如何解决此错误?
答案 0 :(得分:2)
你的BitmapImage很可能会泄漏内存
请务必将UriSource
设置为null,以便释放内存。
请查看http://blogs.msdn.com/b/swick/archive/2011/04/07/image-tips-for-windows-phone-7.aspx了解更多信息。