/// <summary> /// 使用System.Drawing.Image创建WPF使用的ImageSource类型缩略图(不放大小图) /// </summary> /// <param name="sourceImage">System.Drawing.Image 对象</param> /// <param name="width">指定宽度</param> /// <param name="height">指定高度</param> public static ImageSource CreateImageSourceThumbnia(System.Drawing.Image sourceImage, double width, double height) { if (sourceImage == null) { return(null); } double rw = width / sourceImage.Width; double rh = height / sourceImage.Height; var aspect = (float)Math.Min(rw, rh); int w = sourceImage.Width, h = sourceImage.Height; if (aspect < 1) { w = (int)Math.Round(sourceImage.Width * aspect); h = (int)Math.Round(sourceImage.Height * aspect); } Bitmap sourceBmp = new Bitmap(sourceImage, w, h); IntPtr hBitmap = sourceBmp.GetHbitmap(); BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); if (!bitmapSource.IsFrozen && bitmapSource.CanFreeze) { bitmapSource.Freeze(); } Win32Helper.DeleteObject(hBitmap); sourceImage.Dispose(); sourceBmp.Dispose(); return(bitmapSource); }
/// <summary> /// 从一个Bitmap创建ImageSource /// </summary> /// <param name="image">Bitmap对象</param> /// <returns></returns> public static ImageSource CreateImageSourceFromImage(Bitmap image) { if (image == null) { return(null); } try { IntPtr ptr = image.GetHbitmap(); BitmapSource bs = Imaging.CreateBitmapSourceFromHBitmap(ptr, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); if (!bs.IsFrozen && bs.CanFreeze) { bs.Freeze(); } image.Dispose(); Win32Helper.DeleteObject(ptr); return(bs); } catch (Exception) { return(null); } }