5

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.

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, I've tested all options. Also OnLoad. But it doesn't work. I need a method to load the BitmapImage, also when the Image is not being displayed. Regards
The problem is that you are setting the UriSource before setting the cache options (in the constructor parameter). See my edit. Sorry, can't test it right now, but I guess that's the problem.
I have added a answer. Below my Question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.