在FlowDocument中添加图像时出错

时间:2014-05-07 15:32:13

标签: c# wpf image flowdocument

我正在使用此代码将图像添加到FlowDocument

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

然而,我收到此错误:

  

参数1:无法从'System.Drawing.Image'转换为'System.Windows.UIElement'

如何将图像添加到FlowDocument?

3 个答案:

答案 0 :(得分:0)

您想使用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;
}

答案 1 :(得分:0)

您必须将WPF System.Drawing.Bitmap控件放入BlockUIContainer中,而不是System.Windows.Controls.Image。首先,您必须将Bitmap转换为可以用作Source的{​​{1}}的内容,例如Image。 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));

答案 2 :(得分:0)

为您的资源添加完全绝对值,如下所示:

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

......它会起作用。