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 } }