How to save a WPF BitmapSource image to a file?
Asked Answered
E

2

43

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?

Escurial answered 24/5, 2010 at 21:24 Comment(0)
A
88

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

Antiphrasis answered 24/5, 2010 at 21:47 Comment(4)
This does not compile on my machine. BitmapFrame.Create parameters are URI or stream, not image :\Ticker
@IgnacioSolerGarcia This method does exist in WPF: msdn.microsoft.com/en-us/library/ms615993(v=vs.110).aspx. What kind of app are you making?Antiphrasis
You're right, sorry. I did a fast proof of concept app with WinForms.Ticker
This does not work when the saved request comes from a different thread.Flatter
G
3

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);
    }
}
Gunman answered 21/2, 2021 at 17:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.