How to save a WPF BitmapSource image to a file?

后端 未结 1 747
长发绾君心
长发绾君心 2020-12-25 11:09

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 sav

相关标签:
1条回答
  • 2020-12-25 11:18

    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

    0 讨论(0)
提交回复
热议问题