如何把drawing图像转换成wpf控件的source

此例以canvas为例

<Canvas>
  <Image Stretch="Fill" Width="100" Height="100" x:Name="myImage"/>
</Canvas>

一种方法:
System.Drawing.Image bmp=...; // 自己初始化的有效的 image
System.IO.MemoryStream ms = new System.IO.MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);// 格式自处理,这里用 bitmap
  // 下行,初始一个 ImageSource 作为 myImage 的Source
System.Windows.Media.Imaging.BitmapImage bi=new System.Windows.Media.Imaging.BitmapImage();
bi.BeginInit();
bi.StreamSource = new MemoryStream(ms.ToArray()); // 不要直接使用 ms
bi.EndInit();
myImage.Source = bi; // done!
ms.Close();

另一个方法(更加常用的方法):
System.Drawing.Image bmp=...; // 自己初始化的有效的 image
System.Windows.Media.Imaging.BitmapSource bi =
    System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
            bmp.GetHbitmap(),
            IntPtr.Zero,
            Int32Rect.Empty,
            BitmapSizeOptions.FromEmptyOptions());
  // 上面以 bmp 格式为例的,其他格式自处理
myImage.Source = bi; // Done!

参考一下System.Windows.Interop.Imaging 的以下方法:
CreateBitmapSourceFromHBitmap()       // 从 HBITMAP 得到 ImageSource
CreateBitmapSourceFromHIcon()         // 从 HICON 得到 ImageSource
CreateBitmapSourceFromMemorySection() // 从 HMEM 得到 ImageSource

以下附加以下工作中的实例代码段:

            CaptureImageTool capture = new CaptureImageTool();
            if (capture.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                System.Drawing.Image image = capture.Image; // get drawing image
                Bitmap bmp = new Bitmap(image);             // get bitmap
                System.Windows.Media.Imaging.BitmapSource bmpResource =
                    System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(),
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions()); //to bitmap resource
                image1.Source = bmpResource;               //done
            }

 

posted @   卖雨伞的小男孩  阅读(759)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示