3

当我尝试将一些图像保存到我的独立存储时,会发生内存不足异常。如果图像计数超过 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();
    }
}

我该如何解决这个错误?

4

1 回答 1

2

您的 BitmapImage 很可能会泄漏内存。
请务必将 设置UriSource为 null 以便释放内存。

Have a look at http://blogs.msdn.com/b/swick/archive/2011/04/07/image-tips-for-windows-phone-7.aspx for more.

于 2012-09-04T15:53:58.647 回答