Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preload image resources using .NET/WPF

I want to preload my image resources when the application is starting. The images should be cached in the application memory. So I can use the preloaded images in my application.

The problem, if I load a specific View with a lot of images inside, the application hangs a few seconds, after that the view will appear. The application is XAML-based, but the source-property of the image-controls is dynamically changed.

I've tested a few things, but nothing seems to work.

var uri = new Uri ( "pack://application:,,,/Vibrafit.Demo;component/Resources/myImage.jpg", UriKind.RelativeOrAbsolute ); //unit.Image1Uri;
var src = new BitmapImage ( uri );
src.CacheOption = BitmapCacheOption.None;
src.CreateOptions = BitmapCreateOptions.None;

src.DownloadFailed += delegate {
    Console.WriteLine ( "Failed" );
};

src.DownloadProgress += delegate {
    Console.WriteLine ( "Progress" );
};

src.DownloadCompleted += delegate {
    Console.WriteLine ( "Completed" );
};

but the image will not load. The only way to load the image is to show it on the screen within a Image-Control and assign the Source-Property to my newly created BitmapImage-Object. But I don't want to show all images at the startup.

like image 436
RonnyCSHARP Avatar asked Nov 09 '22 18:11

RonnyCSHARP


1 Answers

If you want the image to be loaded immediately, you need to set this cache option:

src.CacheOption = BitmapCacheOption.OnLoad;

Otherwise, it's loaded on demand the first time you access the data (or, in your case, every time you try to access the image data, since you are choosing None).

See the documentation

Also, you are setting the UriSource before setting the cache options. So try something like (out of my head, can't test right now):

var uri = new Uri ( "pack://application:,,,/Vibrafit.Demo;component/Resources/myImage.jpg", UriKind.RelativeOrAbsolute ); //unit.Image1Uri;
var src = new BitmapImage ();
src.BeginInit();
src.CacheOption = BitmapCacheOption.OnLoad;
src.CreateOptions = BitmapCreateOptions.None;
src.DownloadFailed += delegate {
    Console.WriteLine ( "Failed" );
};

src.DownloadProgress += delegate {
    Console.WriteLine ( "Progress" );
};

src.DownloadCompleted += delegate {
    Console.WriteLine ( "Completed" );
};
src.UriSource = uri;
src.EndInit();
like image 78
Jcl Avatar answered Nov 15 '22 07:11

Jcl