Create BitmapFrame asynchronously in an async method

前端 未结 1 746
谎友^
谎友^ 2021-01-27 09:38

Anyone knows how to create BitmapFrame asynchronously in WPF?

I want to batch print XAML Image element whose Source property is se

相关标签:
1条回答
  • 2021-01-27 10:24

    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);
            }
        });
    }
    
    0 讨论(0)
提交回复
热议问题