Load a WPF BitmapImage from a System.Drawing.Bitmap

前端 未结 10 2053
天涯浪人
天涯浪人 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条回答
  •  青春惊慌失措
    2020-11-22 05:08

    My take on this built from a number of resources. https://stackoverflow.com/a/7035036 https://stackoverflow.com/a/1470182/360211

    using System;
    using System.Drawing;
    using System.Runtime.ConstrainedExecution;
    using System.Runtime.InteropServices;
    using System.Security;
    using System.Windows;
    using System.Windows.Interop;
    using System.Windows.Media.Imaging;
    using Microsoft.Win32.SafeHandles;
    
    namespace WpfHelpers
    {
        public static class BitmapToBitmapSource
        {
            public static BitmapSource ToBitmapSource(this Bitmap source)
            {
                using (var handle = new SafeHBitmapHandle(source))
                {
                    return Imaging.CreateBitmapSourceFromHBitmap(handle.DangerousGetHandle(),
                        IntPtr.Zero, Int32Rect.Empty,
                        BitmapSizeOptions.FromEmptyOptions());
                }
            }
    
            [DllImport("gdi32")]
            private static extern int DeleteObject(IntPtr o);
    
            private sealed class SafeHBitmapHandle : SafeHandleZeroOrMinusOneIsInvalid
            {
                [SecurityCritical]
                public SafeHBitmapHandle(Bitmap bitmap)
                    : base(true)
                {
                    SetHandle(bitmap.GetHbitmap());
                }
    
                [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
                protected override bool ReleaseHandle()
                {
                    return DeleteObject(handle) > 0;
                }
            }
        }
    }
    

提交回复
热议问题