`

Convert from System.Drawing.Icon to System.Media.ImageSource and vice versa

    博客分类:
  • WPF
wpf 
阅读更多

with the transition from Winform to WPF, there is rising/upsurging demand to convert from System.Drawing.Icon to System.Media.ImageSource and vice versa (you cannot rule out the possibility to host new tech object in old ones)

 

Below shows how you can do to convert from System.Drwing.Icon to ImageSource.

 

 

 

internal static class IconUtilities
  {
    // you may refer to this page for details on how to convert from System.Drawing.Icon to System.Media.ImageSource
    // http://stackoverflow.com/questions/1127647/convert-system-drawing-icon-to-system-media-imagesource
    [DllImport("gdi32.dll", SetLastError = true)]
    private static extern bool DeleteObject(IntPtr hObject);

    public static ImageSource ToImageSource(this Icon icon)
    {
      Bitmap bitmap = icon.ToBitmap();
      IntPtr hBitmap = bitmap.GetHbitmap();

      ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap(
          hBitmap,
          IntPtr.Zero,
          Int32Rect.Empty,
          BitmapSizeOptions.FromEmptyOptions());

      if (!DeleteObject(hBitmap))
      {
        throw new Win32Exception();
      }

      return wpfBitmap;
    }
  }
 

 

 

note: the referenced material, contains more solution to do the conversion:

 

 

 

withou losing fairness, here is the code that uses the MemoryStream,

 

 

 

public static ImageSource ToImageSourceWithMemoryStream(this Icon icon)
    {
      using (System.IO.MemoryStream iconstream = new System.IO.MemoryStream())
      {
        icon.Save(iconstream);
        iconstream.Seek(0, System.IO.SeekOrigin.Begin);
        return System.Windows.Media.Imaging.BitmapFrame.Create(iconstream);
      }

    }
 

 

 

 

And you may wonder how do we do the reverse, that is from System.Windows.Media.Imaging.ImageSource  or one of its descendant class, that is called System.Windows.Media.Imaging.BitmapSource to System.Drawing.Bitmap...

 

Here is one code, however, please be noted, the code has not been fully testified,  it may work as expected or it may not. 

 

 

internal static class BitmapSourceUtilities
  {

    public static Bitmap ToBitmap(this BitmapSource imageSource, double width, double height)
    {

      double newwidthratio = width / (double)imageSource.PixelWidth;
      // have no idea why the calculation is as such
      double newheightratio = width * (double)imageSource.PixelHeight / (double)imageSource.PixelHeight / (double) imageSource.PixelWidth;

      BitmapSource transformedBitmapSource = new TransformedBitmap(
        imageSource,
        new ScaleTransform(newwidthratio, newheightratio)
        );
      int bitmapwidth = transformedBitmapSource.PixelWidth;
      int bitmapheight = transformedBitmapSource.PixelHeight;
      int stride = bitmapwidth * (transformedBitmapSource.Format.BitsPerPixel + 7) / 8);

      byte[] bits = new byte[bitmapheight * stride];


      transformedBitmapSource.CopyPixels(bits, stride, 0);

      // you may want to put the following code that has the unsafe compiler turned on....
      unsafe
      {
        fixed (byte* pBits = bits)
        {
          IntPtr ptr = new IntPtr(pBits);
          System.Drawing.Bitmap bitmap = new Bitmap(
            bitmapwidth, 
            bitmapheight,
            stride, 
            System.Drawing.Imaging.PixelFormat.Format32bppArgb,
            ptr);
          return bitmap;
        }
      }
    }
  }
 

 

another note is that : The above code references the BitmapSource-Bitmap interop. you may find some boilerplat code that do grayscale and others..

 

 

 

note: synonym of rising..

 

 

climbing

Synonyms:

 

advancing, ascending, emerging, going up,growingincreasingmounting, skyrocketing,soaring, spiraling, surging, upsurging
分享到:
评论

相关推荐

    MySQL 5.6 Reference Manual

    Table of Contents Preface, Notes, Licenses . . . . . . . . ....1. Licenses for Third-Party Components ....1.1. FindGTest.cmake License ....1.2. LPeg Library License ....1.3. LuaFileSystem Library License ....

    CommonsWare.The.Busy.Coders.Guide.to.Android.Development.Version.8.2.2017

    Along the way, it covers how to embed the WebKit Web browser in your application, how to have your application use data from other installed applications (and vice versa!) or off the Internet, and ...

    The.Busy.Coders.Guide.to.Android.Development.Version.8.3.epub

    Along the way, it covers how to embed the WebKit Web browser in your application, how to have your application use data from other installed applications (and vice versa!) or off the Internet, and ...

    ICO图标制作工具ICO图标制作工具

    Convert your Macintosh icons to Windows icons and vice versa. With IcoFX you can extract icons from other files, including Windows Vista and Macintosh files. You can easily work with multiple files ...

    FlexGraphics_V_1.79_D4-XE10.2_Downloadly.ir

    - ADD: Add TFlexPanel.InvalidateControl virtual method which calls from TFlexControl.Invalidate and can be overriden (it is possible now to catch all object invalidation calls). - FIX: The TFlexPanel....

    ADB and Fastboot Tools v1.4.3

    What is this?...If you have previously installed it as system-wide and now you want it current user only (or vice-versa), it won't remove it, you must do it yourself. (at least for now)

    VB编程资源大全(英文源码 其它)

    but nothing for converting from Octal and Hex to decimal (correct us if we are wrong), or from binary to decimal and vice-versa. This sample code does just that. If you do any kind <END><br>55,...

    javacv-platform-1.3.3-src

    // - To get a BufferedImage from an IplImage, or vice versa, we can chain calls to // Java2DFrameConverter and OpenCVFrameConverter, one after the other. // - Java2DFrameConverter also has static ...

    apktool documentation

    In addition to XMLs, resources such as 9 patch images, layouts, strings and much more are correctly decoded to source form. Decoding The decode option on Apktool can be invoked either from d or ...

    NativeJpg 控件

    generate bitmaps from the compressed data and vice versa. It also provides for methods to access the meta data in the files, and methods to manipulate the Jpeg file in a lossless way (rotation/...

    Fading from color to grayscale and vice-versa淡色效果(7KB)

    【淡色效果实现详解】 在计算机图形学中,淡入淡出效果,即从彩色渐变到灰度或反之,是一种常见的视觉过渡技术,广泛应用于图像处理、动画制作以及用户界面设计中。这种效果能够平滑地改变图像的视觉感受,增加动态...

    第三方库NetTopologySuite.IO 提供WKB转WKT,IGeomtry转WKT类库

    This class is used to convert a GeoAPI Geometry to ESRI and vice-versa. It can also convert a ESRI Geometry to WKB/WKT and vice-versa.

    nativejpg v1.24

    generate bitmaps from the compressed data and vice versa. It also provides for methods to access the meta data in the files, and methods to manipulate the Jpeg file in a lossless way (rotation/...

    Convert Word to PDF 1.5_0.crx

    几种常用文件类型相互转换。The #1 Converter tool that supports PDF, Word, Excel, PPT, JPG. Convert PDF to different formats and vice versa in one click.

    C++XML文件解析库tinyxml

    I've also tried to include some C++ tips like how to convert strings to integers and vice versa. This isn't anything to do with TinyXML itself, but it may helpful for your project so I've put it in ...

    INTRODUCTION TO PYTHON SCRIPTING FOR MAYA ARTISTS.

    Python can call MEL scripts and vice versa, allowing for seamless integration between the two languages. **Maya Python Standalone Applications** Developing standalone applications using Python and ...

    Kerberos Administration Guide

    The Kerberos protocol uses strong cryptography so that a client can prove its identity to a server (and vice versa) across an insecure network connection. After a client and server has used Kerberos ...

    WinHex_14.2_SR-3_SC

    For example, "clusters" are defined by the file system, the allocation of clusters to files (and vice versa) is known to WinHex, "free space" and "slack space" have a meaning. If you need to edit ...

    EurekaLog_7.5.0.0_Enterprise

    4)....Added "--el_injectjcl", "--el_createjcl", and "--el_createdbg" command-line options for ecc32/emake to inject JEDI/JCL debug info, create .jdbg file, and create .dbg file (Microsoft debug format...

Global site tag (gtag.js) - Google Analytics