BitmapExt.cs 1.9 KB
Newer Older
潘栩锋's avatar
潘栩锋 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Imaging;

namespace Install.Core.Common
{
    public static class BitmapExt
    {
        #region 基本支持
        [DllImport("gdi32")]
        public static extern int DeleteObject(IntPtr o);
        public static BitmapSource CreateBitmapSourceFromBitmap(System.Drawing.Bitmap m_Bitmap)
        {
            IntPtr ip = m_Bitmap.GetHbitmap();
            BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                ip, IntPtr.Zero, Int32Rect.Empty,
                System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
            DeleteObject(ip);


            return bitmapSource;
        }
        public static BitmapSource CreateBitmapSource(this System.Drawing.Bitmap bmp)
        {
            return CreateBitmapSourceFromBitmap(bmp);
        }

        public static void ToBitmapImage(this System.Drawing.Bitmap bmp, System.Windows.Media.Imaging.BitmapImage bitmapImage)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);// 格式自处理,这里用 bitmap

            // 初始一个 ImageSource 作为 myImage 的Source
            bitmapImage.BeginInit();

            bitmapImage.StreamSource = new MemoryStream(ms.ToArray()); // 不要直接使用 ms
            bitmapImage.EndInit();
            ms.Close();
        }
        public static System.Windows.Media.Imaging.BitmapImage CreateBitmapImage(this System.Drawing.Bitmap bmp)
        {
            System.Windows.Media.Imaging.BitmapImage bitmapImage = new BitmapImage();
            bmp.ToBitmapImage(bitmapImage);
            return bitmapImage;

        }

        #endregion
    }
}