C#:System.Windows.Controls.Image存为BMP及Excel水印转换后Image.Source为空问题
我来帮你解决这两个C#相关的问题哈~
问题1:如何将C#中的System.Windows.Controls.Image保存为.bmp格式文件?
要把WPF的System.Windows.Controls.Image控件保存为BMP文件,核心是处理它的Source属性(本质是BitmapSource类型),用WPF自带的图像编码器来完成编码和保存:
- 首先确认控件的
Source不为空,且是有效的BitmapSource类型 - 然后创建
BmpBitmapEncoder——这是WPF专门用于生成BMP格式的编码器 - 将
BitmapSource作为帧添加到编码器中 - 最后通过文件流将编码器内容写入目标文件
示例代码如下:
using System.IO; using System.Windows.Media.Imaging; using System.Windows.Controls; public void SaveWpfImageAsBmp(Image wpfImage, string outputPath) { // 校验Source的有效性 if (wpfImage.Source is not BitmapSource bitmapSource) { throw new InvalidOperationException("Image控件的Source不是有效的BitmapSource"); } // 初始化BMP编码器并添加图像帧 var bmpEncoder = new BmpBitmapEncoder(); bmpEncoder.Frames.Add(BitmapFrame.Create(bitmapSource)); // 将编码后的内容写入文件 using (var fileStream = new FileStream(outputPath, FileMode.Create)) { bmpEncoder.Save(fileStream); } }
问题2:转换System.Drawing.Image到WPF Image时Source为空的问题
看你的代码,问题出在流的位置未重置和缺少初始化收尾调用,导致BitmapImage没有正确加载流内容。修正后的完整步骤和代码如下:
- 把
System.Drawing.Image保存到MemoryStream后,必须将流的位置重置到开头(ms.Position = 0),否则BitmapImage会从流的末尾开始读取,自然读不到内容 - 调用
ix.EndInit()完成BitmapImage的初始化,这是WPF图像对象初始化的必要步骤 - 别忘了用
using包裹MemoryStream,确保流能被正确释放;BitmapCacheOption.OnLoad设置也很关键,它会让图像立即加载流内容,避免流关闭后图像失效
修正后的代码:
using System.IO; using System.Drawing; using System.Windows.Controls; using System.Windows.Media.Imaging; // 假设imgWtrmrk是你已创建好的System.Drawing.Image对象 using (MemoryStream ms = new MemoryStream()) { imgWtrmrk.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); // 关键:重置流指针到起始位置 ms.Position = 0; System.Windows.Controls.Image image = new System.Windows.Controls.Image(); BitmapImage ix = new BitmapImage(); ix.BeginInit(); ix.CacheOption = BitmapCacheOption.OnLoad; ix.StreamSource = ms; ix.EndInit(); // 必须调用此方法完成初始化 // 赋值给Image控件的Source image.Source = ix; // 现在image对象的Source就不再为空了 }
内容的提问来源于stack exchange,提问作者murat turna
相关产品推荐
相关产品推荐

