0

Anyone knows how to create BitmapFrame asynchronously in WPF?

I want to batch print XAML Image element whose Source property is set code behind. Here LogoImageUrl is the URL of the web image I want to load asynchronously.

LogoImage.Source = BitmapFrame.Create(new Uri(LogoImageUrl));

Can I create an async method like this:

public async Task<BitmapFrame> GetBitmapFrame(Uri uri)
{
    await ... // What to be awaited?

    return BitmapFrame.Create(uri);
}

...so I can use that method in a try block and then print it in finally block?

7
  • 1
    You can use IsAsync property of the binding to achieve that. Commented Feb 21, 2017 at 8:23
  • Are your loading local or remote (web) image files? Commented Feb 21, 2017 at 8:35
  • @Clemens I want to load web image. Commented Feb 21, 2017 at 8:41
  • Does it really have to be a BitmapFrame? Commented Feb 21, 2017 at 8:49
  • @Clemens Sorry, but yeah, I have to use BitmapFrame. Commented Feb 21, 2017 at 8:51

1 Answer 1

1

You should asynchronously download the web image and create a BitmapFrame from the downloaded buffer:

public async Task<BitmapFrame> GetBitmapFrame(Uri uri)
{
    var httpClient = new System.Net.Http.HttpClient();
    var buffer = await httpClient.GetByteArrayAsync(uri);

    using (var stream = new MemoryStream(buffer))
    {
        return BitmapFrame.Create(
            stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
    }
}

Since the BitmapFrame.Create call in the above example return a frozen BitmapFrame, you may also create the BitmapFrame asynchronously (although I doubt it's necessary).

public async Task<BitmapFrame> GetBitmapFrame(Uri uri)
{
    var httpClient = new System.Net.Http.HttpClient();
    var buffer = await httpClient.GetByteArrayAsync(uri);

    return await Task.Run(() =>
    {
        using (var stream = new MemoryStream(buffer))
        {
            return BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
        }
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Duh, how can I not think of HttpClient... Thanks, it works!

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.