Search code examples
c#uwpwin2d

Converting a Win2D CanvasRenderTarget to a BitmapImage?


I'm trying to write a function which accepts my ICanvasEffect as a parameter (which in my case is a Win2D BlendEffect), and I want to convert the CanvasRenderTarget to a BitmapImage so that I can use it in a UWP Image control:

    private async Task<BitmapImage> GetBitmapImage(CancellationToken ct, ICanvasImage effect)
    {
        using (var target = new CanvasRenderTarget(CanvasDevice.GetSharedDevice(), 320f, 240f, 96))
        {
            using (var ds = target.CreateDrawingSession())
            {
                // Draw the image with the supplied ICanvasImage
                ds.DrawImage(effect);
            }

            //await target.SaveAsync(outputStream, CanvasBitmapFileFormat.Jpeg).AsTask(ct);
        }
    }

As you see in the commented code, CanvasRenderTarget has a SaveAsync method I can use to save it to a Stream, but how?


Solution

  • Figured it out:

        using (var stream = new InMemoryRandomAccessStream())
        {
            await target.SaveAsync(stream, CanvasBitmapFileFormat.Jpeg).AsTask(ct);
    
            var bmp = new BitmapImage();
    
            stream.Seek(0);
            await bmp.SetSourceAsync(stream);
        }