How to save a WPF BitmapSource image to a file?

痴心易碎 提交于 2019-11-28 23:46:39

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/2900447/how-to-save-a-wpf-bitmapsource-image-to-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!