Should I store `ImageSource` or instantiate it on demand?

49 Views Asked by At

I'm designing a mechanism similar to Microsoft SDK's CrispImage. The idea is to render and cache images from SVGs basing on requested resolution and current DPI. I also need to be able to save and load built cache, so that I won't have to re-render images, which already have been rendered in the future.

Since I'm writing all that for WPF, I subclassed Image, which is supposed to be used like following:

<c:CrispImage Width="16" Height="16" ImageResource="Arrow" />

I achieve that by internally binding Source property to some other properties:

public CrispImage()
{
  var sourceBinding = new MultiBinding();
  sourceBinding.Bindings.Add(new Binding { Source = this, Path = new PropertyPath(nameof(Dpi)) });
  sourceBinding.Bindings.Add(new Binding { Source = this, Path = new PropertyPath(nameof(ImageResource)) });
  sourceBinding.Bindings.Add(new Binding { Source = this, Path = new PropertyPath(nameof(Width)) });
  sourceBinding.Bindings.Add(new Binding { Source = this, Path = new PropertyPath(nameof(Height)) });
  sourceBinding.Converter = new CrispImageSourceConverter();

  this.SetBinding(SourceProperty, sourceBinding);
}

In the end I need to provide image as a ImageSource (BitmapSource in my case). And here's where I have the question:

Can I cache ImageSources or should I create them always on demand from Bitmaps, which I keep in memory?

The reasons, why I ask:

  • I don't know, if ImageSource can be cached and reused in multiple places?
  • Does created BitmapImageSource contain inside the Bitmap's instance itself? Or does it copy it? (since I need to keep those Bitmaps to save them into cache, I'd end up in having twice as much memory occupied by them)
  • If I need to re-create 100 images (for instance to display multiple images on a toolbar), is it fast enough to create all them as BitmapSources from Bitmaps on the fly or should I use cached instances instead?
0

There are 0 best solutions below