【问题标题】:How to convert Image to ImageSource如何将图像转换为图像源
【发布时间】:2017-03-03 16:14:02
【问题描述】:

我什至不知道我是否问对了问题;所以提前道歉。我正在将一些 PNG 写入画布,并且我还想同时将这些 PNG 复制到位图。我希望 PNG 出现在位图上与画布上相同的位置。

这是代码sn-p:

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,这个错误会得到解决吗?还是我做错了?

谢谢!

【问题讨论】:

  • 在上面的代码中,您创建一个BitmapImage对象,它一个ImageSource(标准OOP/Liskov替换/等等。 )。你为什么不直接使用那个对象?您为什么要尝试将 WPF UI 元素转换为不是的东西?

标签: c# wpf bitmap rendertargetbitmap drawingvisual


【解决方案1】:

如果直接绘制BitmapImage,应该可以工作

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

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

【讨论】:

  • 谢谢!非常感谢!
【解决方案2】:

Image 是窗口上的控件。 Image.SourceImage 检索到的实际位图以进行渲染。这可能并不明显,但您的代码确实暗示了这一点,因为您将 Source 设置为您的 BitmapImage

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

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

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

【讨论】:

  • 感谢您的解释!
【解决方案3】:

在这里试试这个

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

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多