BitmapとImageSourceの変換

4638 ワード

    public class ImageConverter

    {

        [DllImport("gdi32.dll", SetLastError = true)]

        private static extern bool DeleteObject(IntPtr hObject);

        /// <summary>

        ///  bitmap ImageSource

        /// </summary>

        /// <param name="icon"></param>

        /// <returns></returns>

        public static ImageSource ChangeBitmapToImageSource(Bitmap bitmap)

        {

            IntPtr hBitmap = bitmap.GetHbitmap();

            ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(

                hBitmap,

                IntPtr.Zero,

                Int32Rect.Empty,

                BitmapSizeOptions.FromEmptyOptions());

            if (!DeleteObject(hBitmap))// 。 。

            {

                throw new System.ComponentModel.Win32Exception();

            }

            return wpfBitmap;

        }

        /// <summary>

        ///  Bitmap BitmapSource

        /// </summary>

        /// <param name="bmp"></param>

        /// <returns></returns>

        public static BitmapSource ChangeBitmapToBitmapSource(Bitmap bmp)

        {

            BitmapSource returnSource;

            try

            {

                returnSource = Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

            }

            catch

            {

                returnSource = null;

            }

            return returnSource;

        }

        /// <summary>

        ///  Icon ImageSource 

        /// </summary>

        public ImageSource ChangeIconToImageSource(Icon icon)

        {

            ImageSource imageSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(

            icon.Handle,

            Int32Rect.Empty,

            BitmapSizeOptions.FromEmptyOptions());

            return imageSource;

        }

    }