如何将窗口的图标转换为位图图像
本文关键字:转换 位图 图像 图标 窗口 | 更新日期: 2023-09-27 18:14:15
我正在尝试帮助这个线程将图像源转换为位图图像 - WPF 将我的窗口icon
类型为 ImageSource
转换为 BitmapImage
:
var bi = _window.Icon as BitmapImage;
问题是转换没有发生(执行此行后 bi 为空(,我确定_window.Icon
不为空,任何人都可以告诉我为什么这种转换没有发生?
更新:
虽然Visual Studio文档说Window.Icon是tyme ImageSource
,但调试器说它是一个System.Windows.Media.Imaging.BitmapFrameDecode
做的时候:
var bi = (BitmapImage) _window.Icon;
我得到以下异常:
其他信息:无法强制转换类型的对象 "System.Windows.Media.Imaging.BitmapFrameDecode"键入 "System.Windows.Media.Imaging.BitmapImage"。
问题是转换没有发生(执行此行后 bi 为空(,我确信_window。图标不为空
它不是空的,但它可能不是BitmapImage
.Window.Icon
是ImageSource
型,BitmapImage
是从中派生出来的。在 XAML 中设置图标时,图像的类型通常为 System.Windows.Media.Imaging.BitmapFrameDecode
,这是派生自 BitmapFrame
的内部类;所以这不是一个BitmapImage
,这就是演员阵容失败的原因。
编辑:如果你只需要将图标转换为System.Drawing.Bitmap
,你不需要BitmapImage
;一个BitmapSource
就足够了。
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create((BitmapSource)_window.Icon));
using (var stream = new MemoryStream()))
{
encoder.Save(stream);
stream.Position = 0; // rewind the stream
var bitmap = (System.Drawing.Bitmap)System.Drawing.Image.FromStream(stream);
var icon = System.Drawing.Icon.FromHandle(bitmap.GetHicon());
}
不知道为什么你需要投射到BitmapImage
.在每种实际情况下,转换为BitmapSource
就足够了(这是BitmapImage
和BitmapFrame
的共同基类(:
var bitmap = _window.Icon as BitmapSource;
BitmapSource
提供了所有相关的位图属性,如PixelWidth
、PixelHeigth
、DpiX
、DpiY
、Format
等。