如何将图像转换为图像源

How to convert Image to ImageSource

我什至不知道我是否在问正确的问题;所以提前道歉。我正在将一些 PNG 写入 canvas 并且我还想同时将 PNG 复制到位图。我希望 PNG 出现在位图上与它们在 canvas.

上相同的位置

这是代码片段:

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);

但是,它抛出错误“无法从 'System.Windows.Controls.Image' 转换为 'System.Windows.Media.ImageSource' 这一行:

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

如果我能以某种方式将图像转换为 ImageSource,这个错误是否会得到解决?还是我的做法全错了?

谢谢!

Image是window上的控件。 Image.SourceImage 检索到要呈现的实际位图。它可能并不明显,但您的代码确实对此有所暗示,因为您将 Source 设置为 BitmapImage.

您需要使用源 属性 才能获得实例化的实际 BitmapImage

您可能需要投射,但这应该有效:

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

直接绘制BitmapImage应该可以

var source = new BitmapImage(new Uri(TreeFile))

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

在这里试试这个

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);