zoukankan      html  css  js  c++  java
  • 如何把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
                }

  • 相关阅读:
    bzoj1257
    bzoj1833
    bzoj3505
    bzoj2226
    bzoj1263
    bzoj2429
    bzoj1854
    bzoj3555
    bzoj1877
    放两个模版
  • 原文地址:https://www.cnblogs.com/xietianjiao/p/5646726.html
Copyright © 2011-2022 走看看