2

From what I've seen, WPF images' source is a BitmapSource object while the Resources images are read as bitmap. I've easily found a way to convert images from Bitmap format into BitmapSource format but I believe that running this conversion every time I need an image is just costly in terms of performance and memory consumption (The Bitmaps themselves are static but I guess that the conversion allocates a new object in memory for the BitmapSource).

I thought about holding an in-memory, lazy cache for the BitmapSource objects, that way I will only need to run the conversion once per image. However, I find it hard to believe that this is the proper solution for this issue.

The nature of the application is that the data extends over time and the business objects are never disposed. Therefore, this assumption will only hold in case the implementation will hold static resources for these static images.

I will very much appreciate the proper solution for this issue.

sagibb
  • 956
  • 2
  • 9
  • 21

1 Answers1

2

I'm not sure I understand what you mean but you can use Image from Resources like this.
If you have an Image resource named "B1.png" and you set "Build Action" to "Resource" for it than you can use it in xaml like this.

<Image Name="c_image" Source="/YourAssemblyName;component/Resources/B1.png" />

and in code behind like this

Image img = new Image();
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit(); 
bitmapImage.UriSource = new Uri("pack://application:,,,/YourAssemblyName;component/Resources/B1.png"); 
bitmapImage.EndInit(); 
img.Source = bitmapImage;
Fredrik Hedblad
  • 83,499
  • 23
  • 264
  • 266
  • Meleak, thanks for the answer. I am also not sure that I understand your solution. I have two questions: 1. Is the code behind mandatory? Can the resource be used directly in the XAML? 2. Do you know whether the WPF framework will run the conversion behind the stage or is this code really more effective? – sagibb Nov 23 '10 at 07:50
  • @tutipute: The code behind is only for creating an image in code behind. The xaml way uses no code behind (so yes, can be used directly in xaml). If you add an image in the designer, view properties for it and press Source then you can choose the source from a dialog (all applicable resources will be shown). After that you can inspect the uri in xaml. Note that the build action for the resource must be set to Resource. – Fredrik Hedblad Nov 23 '10 at 10:20
  • @tutipute: To answer question 2: This is the way to use resources for Image in WPF, so I'm sure it's pretty optimized. – Fredrik Hedblad Nov 23 '10 at 10:25
  • @Meleak, hey bro what is the /YourAssemblyName? is this the resx file? and what is the component/Resources ? I don't get this path, thanks – franko_camron Sep 07 '11 at 22:12