Out of memory exception in WP7

2019-04-12 06:49发布

When I am trying to save some images to my IsolatedStorage there is an Out of Memory exception occures. If the image count is more than 20 this error occurs. I am downloading all these images and save them in a temp folder in isolated storage. When I am trying to save these images from temp folder to a folder named myImages in isolated storage, this error occurs. Each photo is read from temp and write to myImages one by one. When some 20 or 25 photos are saved to myImages then this error occures. Images has an average size of 350-400 KB. How can I avoid this error?

My Code is :

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();
    }
}

how can I fix this error?

1条回答
老娘就宠你
2楼-- · 2019-04-12 07:20

Your BitmapImage is most likely leaking the memory.
Be sure to set the UriSource to null so that the memory is freed.

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

查看更多
登录 后发表回答