• 如何把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
                }

  • 相关阅读:
    说一下Mysql索引
    B树、B-树、B+树、B*树之间的关系
    Mybatis Plus 的优点
    JVM垃圾回收机制
    Java中的集合
    MQ 面试题
    Redis 双写一致性
    Redis 主从复制
    C#中Abstract和Virtual的区别
    C#设计模式(2)——简单工厂模式
  • 原文地址:https://www.cnblogs.com/xietianjiao/p/5646726.html
Copyright © 2020-2023  润新知