How to store a lot of WriteableBitmap?

168 views Asked by At

I'm working with a set of 400+ images, that I need to modify in different ways. At the end, I need to have almost 1500 images. Let's say they all are 512*512px

I want to first apply this modifications in order to get my 1500 images, and keep all this images in a List, to have a quick access on it in my application (I want to be able to switch between images without any loading time)

To apply my modifications, I use WriteableBitmapEx.

Thing is, to be able to modify it, I need to render this images into WriteableBitmap, and it gives me OutOfMemoryException.

Here is a simplified example of what I'm doing:

        List<WriteableBitmap> myList = new List<WriteableBitmap>();

        foreach (var image in mySetOfImages) // iterating on my set of 400+ images
        {
            WriteableBitmap source = image.RenderImage().As<WriteableBitmap>();

            WriteableBitmap dest1 = BitmapFactory.New(512, 512);
            WriteableBitmap dest2 = BitmapFactory.New(512, 512);

            [...] // Some lines modifying dest1 and dest2 using source

            myList.Add(dest1);
            myList.Add(dest2);
        }

I read a lot about this exception. I read that I could add

GC.Collect();

may be inside my 'foreach', but I think this is going to take to much time to load.

What I read also made me think that may be I'm not doing it the right way and that I should think of another way to do it. That is why I'm posting here, do you guys have any tips?

1

There are 1 answers

0
Lee Campbell On

Basically, you just cant store more than 2GB of stuff in memory on a 32bit .NET process. As pointed out, this isn't a Garbage Collector (GC) issue, as you are strongly referencing all these images by storing them in a List<T>. The Garbage Collector will allocate memory for each of your images, and when it is "under pressure" will try to find objects that are no longer reference, and then release them. However as you only appear to be adding to the list, the pressure will only increase :-(

You have two options, from what I can see:

  1. Find a way to reduce the amount of memory each image is requires to allocated. Most obvious is to reduce the size e.g. only cache a thumbnail. And second is to not cache 2 images for each source image!
  2. Try to lazily load the images only when they are requested, and potentially drop unused (out of view) images from the list. Now you are into creating your own WPF Visualization code for scrolling list etc.