In WPF, the System.Windows.Clipboard.getImage()
function returns a BitmapSource
object. As a newbie in WPF coming from a WinForms background, its not clear to me how to save this image to a file. What are the steps I must take?
Asked
Active
Viewed 5.9k times
43

StayOnTarget
- 11,743
- 10
- 52
- 81

tbischel
- 6,337
- 11
- 51
- 73
2 Answers
86
You need to use an encoder (subclass of BitmapEncoder
). For instance, to save it to the PNG format, you do something like that :
public static void SaveClipboardImageToFile(string filePath)
{
var image = Clipboard.GetImage();
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
encoder.Save(fileStream);
}
}
By the way, note that there's a bug in Clipboard.GetImage
. It shouldn't be a problem if you just save the image to a file, but it will be if you want to display it.
EDIT : the bug mentioned above seems to be fixed in 4.0

Thomas Levesque
- 286,951
- 70
- 623
- 758
-
1This does not compile on my machine. BitmapFrame.Create parameters are URI or stream, not image :\ – Ignacio Soler Garcia Mar 29 '17 at 06:43
-
@IgnacioSolerGarcia This method does exist in WPF: https://msdn.microsoft.com/en-us/library/ms615993(v=vs.110).aspx. What kind of app are you making? – Thomas Levesque Mar 29 '17 at 07:51
-
You're right, sorry. I did a fast proof of concept app with WinForms. – Ignacio Soler Garcia Mar 29 '17 at 17:04
-
This does not work when the saved request comes from a different thread. – Bernhard Hiller Apr 24 '20 at 12:55
2
This clears up the BitmapFrame.Create issue that you have.
public static void SaveClipboardImageToFile(string filePath)
{
//var image = Clipboard.GetImage();
BitmapSource image = (BitmapSource)Clipboard.GetImage();
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
BitmapEncoder encoder = new PngBitmapEncoder();
//encoder.Frames.Add(BitmapFrame.Create(image));
encoder.Frames.Add(BitmapFrame.Create(image As BitmapSource));
encoder.Save(fileStream);
}
}

Jym
- 103
- 5