Search code examples
c#wpfbitmaprendertargetbitmapdrawingvisual

How to convert Image to ImageSource


I don't know if I'm even asking the right question; so apologies in advance. I am writing some PNGs to a canvas and I also want to simultaneously copy the PNGs to a bitmap. I want the PNGs to appear in the same locations on the bitmap as they do on the canvas.

This is the code snippet:

WorkingBMP = new RenderTargetBitmap(BOARD_WIDTH, BOARD_HEIGHT, 96, 96, PixelFormats.Pbgra32);

TreeFile = "pack://application:,,,/Images/" + TreeFile;

var image = new Image
{
    Source = new BitmapImage(new Uri(TreeFile))
};
image.Width = 10;
image.Height = 10;

Canvas.SetLeft(image, x );
Canvas.SetTop(image, y );

DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
drawingContext.DrawImage(image, new Rect(x, y, image.Width, image.Height));
drawingContext.Close();

WorkingBMP.Render(drawingVisual);

MainCanvas.Children.Add(image);

HOWEVER, it throws the error "cannot convert from 'System.Windows.Controls.Image' to 'System.Windows.Media.ImageSource' on this line:

drawingContext.DrawImage(image,
                  new Rect(x, y, image.Width, image.Height));

Will this error be solved if I can somehow convert image to to an ImageSource or am I going about this all wrong?

Thanks!


Solution

  • If BitmapImage drawn directly, it should work

    var source = new BitmapImage(new Uri(TreeFile))
    
    drawingContext.DrawImage(source,
                      new Rect(x, y, image.Width, image.Height));