0

I'm using this code to add an image into a FlowDocument

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

However, I get this error:

Argument 1: cannot convert from 'System.Drawing.Image' to 'System.Windows.UIElement'

How do I add an image into a FlowDocument?

Vinshi
  • 313
  • 2
  • 7
  • 27

3 Answers3

0

You want to use System.Windows.Controls.Image and not System.Drawing.Image.

You can use this bit of code to convert your Drawing.Image to 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;
}
123 456 789 0
  • 10,565
  • 4
  • 43
  • 72
  • I get the same error when I add a BitmapImage as an argument. – Vinshi May 07 '14 at 15:59
  • When i add the System.Windows.Controls.Image, I get an saying "Specified element is already the logical child of another element. Disconnect it first." I don't want to disconnect the image. – Vinshi May 07 '14 at 16:58
  • @Vinshi You don't want to add the `Image` that has a `Parent` to another object. You have to disconnect it. One way is to just create a new `Image` with the copied `source` – 123 456 789 0 May 07 '14 at 16:59
0

Instead of a System.Drawing.Bitmap you have to put a WPF System.Windows.Controls.Image control into the BlockUIContainer. First, you have to convert your Bitmap into something that can by used as the Source of an Image e.g. a WPF BitmapImage. Then you would create a new Image control and add that to your document:

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));
Clemens
  • 123,504
  • 12
  • 155
  • 268
0

Add full absolute to your resource like this:

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

...and it will work.

Tim Malone
  • 3,364
  • 5
  • 37
  • 50