Load a WPF BitmapImage from a System.Drawing.Bitmap

前端 未结 10 2051
天涯浪人
天涯浪人 2020-11-22 04:39

I have an instance of a System.Drawing.Bitmap and would like to make it available to my WPF app in the form of a System.Windows.Media.Imaging.BitmapImage<

10条回答
  •  -上瘾入骨i
    2020-11-22 05:24

    I know this has been answered, but here are a couple of extension methods (for .NET 3.0+) that do the conversion. :)

            /// 
        /// Converts a  into a WPF .
        /// 
        /// The source image.
        /// A BitmapSource
        public static BitmapSource ToBitmapSource(this System.Drawing.Image source)
        {
            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(source);
    
            var bitSrc = bitmap.ToBitmapSource();
    
            bitmap.Dispose();
            bitmap = null;
    
            return bitSrc;
        }
    
        /// 
        /// Converts a  into a WPF .
        /// 
        /// Uses GDI to do the conversion. Hence the call to the marshalled DeleteObject.
        /// 
        /// The source bitmap.
        /// A BitmapSource
        public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)
        {
            BitmapSource bitSrc = null;
    
            var hBitmap = source.GetHbitmap();
    
            try
            {
                bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    hBitmap,
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions());
            }
            catch (Win32Exception)
            {
                bitSrc = null;
            }
            finally
            {
                NativeMethods.DeleteObject(hBitmap);
            }
    
            return bitSrc;
        }
    

    and the NativeMethods class (to appease FxCop)

        /// 
    /// FxCop requires all Marshalled functions to be in a class called NativeMethods.
    /// 
    internal static class NativeMethods
    {
        [DllImport("gdi32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool DeleteObject(IntPtr hObject);
    }
    

提交回复
热议问题