0

How can I retrieve an image copied in a clipboard into System.IO.Stream in C#?

Stream lStream = new MemoryStream();

IDataObject lIDataObj = Clipboard.GetDataObject();

if (lIDataObj.GetDataPresent(DataFormats.Bitmap))
{
  System.Drawing.Image lImage = (System.Drawing.Image)lIDataObj.GetData(DataFormats.Bitmap);

  lImage.Save(lStream, System.Drawing.Imaging.ImageFormat.Jpeg);

  //this.RADRichTextBox.InsertImage(lStream, "jpg");
}
J. Steen
  • 15,470
  • 15
  • 56
  • 63
Alex McManns
  • 81
  • 2
  • 11
  • 2
    What problem do you have? Which part of your code doesn't work? Are you getting errors? – Thorsten Dittmar Nov 24 '16 at 10:51
  • @ThorstenDittmar That's what it says : _Impossible to cast an objet of type 'System.Windows.Interop.InteropBitmap' to type 'System.Drawing.Image'._
    on trying this line : **System.Drawing.Image lImage = (System.Drawing.Image)lIDataObj.GetData(DataFormats.Bitmap);**
    – Alex McManns Nov 24 '16 at 13:10
  • Well, yes, the Clipboard doesn't contain a WPF image. See my answer. – Thorsten Dittmar Nov 24 '16 at 13:15

2 Answers2

1

Based on this SO post, you have to modify the way you populate your stream by :

System.Drawing.Image lImage = (System.Drawing.Image)lIDataObj.GetData(DataFormats.Bitmap);
lStream.Save(lImage, System.Drawing.Imaging.ImageFormat.Jpeg);
Community
  • 1
  • 1
PMerlet
  • 2,568
  • 4
  • 23
  • 39
0

The clipboard does not contain a WPF Image, but a Windows Forms Bitmap. So what you have to do is get the Windows Forms Bitmap first and then convert it to a WPF image.

An example for this can be found here: WPF Image: .Source = Clipboard.GetImage() is not displayed

Community
  • 1
  • 1
Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139