How to convert Image to ImageSource

5.1k Views Asked by At

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!

3

There are 3 best solutions below

1
Arsen Mkrtchyan On BEST ANSWER

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));
1
TyCobb On

Image is the control on the window. Image.Source is the actual bitmap Image retrieves to render. It may not be apparent, but your code does kind of hint at this because you are setting Source to your BitmapImage.

You need to use the source property in order to get your actual BitmapImage you instantiated.

You may need to cast, but this should work:

drawingContext.DrawImage(image.Source,
                  new Rect(x, y, image.Width, image.Height));
0
CaptainHere On

Here Try this

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(new BitmapImage(new Uri(TreeFile)), new Rect(x, y, image.Width, image.Height));
drawingContext.Close();

WorkingBMP.Render(drawingVisual);

MainCanvas.Children.Add(image);