在FlowDocument中添加图像时出错

本文关键字:出错 图像 添加 FlowDocument | 更新日期: 2023-09-27 18:02:24

我使用这个代码添加一个图像到FlowDocument

doc.Blocks.Add(new BlockUIContainer(image));

但是,我得到这个错误:

参数1:不能从'System.Drawing. '转换。映像到System.Windows。UIElement '

如何将图像添加到FlowDocument中?

在FlowDocument中添加图像时出错

您要使用System.Windows.Controls.Image而不是System.Drawing.Image

您可以使用这段代码将Drawing.Image转换为Controls.Image

public static BitmapImage ToWpfImage(this System.Drawing.Image img)
{
  MemoryStream ms=new MemoryStream();  // no using here! BitmapImage will dispose the stream after loading
  img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
  BitmapImage bitMapImage = new BitmapImage();
  bitMapImage.BeginInit();
  bitMapImage.CacheOption=BitmapCacheOption.OnLoad;
  bitMapImage.StreamSource=ms;
  bitMapImage.EndInit();
  return bitMapImage;
}

代替System.Drawing.Bitmap,你必须把WPF System.Windows.Controls.Image控件放入BlockUIContainer。首先,您必须将Bitmap转换为可以用作ImageSource的东西,例如WPF BitmapImage。然后你将创建一个新的Image控件并将其添加到你的文档:

System.Drawing.Bitmap bitmap = ...
var bitmapImage = new BitmapImage();
using (var memoryStream = new MemoryStream())
{
    bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
    bitmapImage.BeginInit();
    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
    bitmapImage.StreamSource = memoryStream;
    bitmapImage.EndInit();
}
var image = new Image
{
    Source = bitmapImage,
    Stretch = Stretch.None
};
doc.Blocks.Add(new BlockUIContainer(image));

给你的资源添加full absolute:

var img = new BitmapImage(new Uri("pack://application:,,,/(your project name);component/Resources/PangoIcon.png", UriKind.RelativeOrAbsolute));

…它会成功的