【问题标题】:Error while adding an image in FlowDocument在 FlowDocument 中添加图像时出错
【发布时间】:2016-07-20 07:20:16
【问题描述】:

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

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

但是,我收到此错误:

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

如何将图像添加到 FlowDocument 中?

【问题讨论】:

    标签: c# wpf image flowdocument


    【解决方案1】:

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

    【讨论】:

    • 当我添加 BitmapImage 作为参数时,我得到了同样的错误。
    • 当我添加 System.Windows.Controls.Image 时,我得到一个说法“指定的元素已经是另一个元素的逻辑子元素。首先断开它。”我不想断开图像。
    • @Vinshi 您不想将具有ParentImage 添加到另一个对象。你必须断开它。一种方法是使用复制的source 创建一个新的Image
    【解决方案2】:

    您必须将 WPF System.Windows.Controls.Image 控件放入 BlockUIContainer 中,而不是 System.Drawing.Bitmap。首先,您必须将您的Bitmap 转换为可以用作SourceImage 的东西,例如一个 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));
    

    【讨论】:

      【解决方案3】:

      像这样向您的资源添加完整的绝对值:

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

      ...它会起作用的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-22
        • 2017-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多