- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.IO;
- using System.Collections;
- using System.Security.Cryptography;
- using System.Windows.Controls;
- using System.ComponentModel;
- using System.Collections.ObjectModel;
- using System.Runtime.InteropServices;
-
- namespace DrawWpf
- {
- class FrmClass
- {
- #region 提供两种给Image的Source赋值的方法
- public static System.Windows.Media.ImageBrush GetImageBrushFrom_PResource(System.Drawing.Bitmap imgSrc)
- {
- System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(imgSrc);
- MemoryStream stream = new MemoryStream();
-
- bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
- System.Windows.Media.ImageBrush imgBrush = new System.Windows.Media.ImageBrush();
- System.Windows.Media.ImageSourceConverter isConverter = new System.Windows.Media.ImageSourceConverter();
- imgBrush.ImageSource = (System.Windows.Media.ImageSource)isConverter.ConvertFrom(stream);
-
- return imgBrush;
- }
-
- [DllImport("gdi32.dll", SetLastError = true)]
- private static extern bool DeleteObject(IntPtr hObject);
- //将 Bitmap转换为BitmapSource
- //使用过System.Drawing.Bitmap后一定要用DeleteObject释放掉对象,不然内存不释放,很快系统内存就消耗光了。
- public static System.Windows.Media.ImageSource BitmapToBitmapSource(System.Drawing.Bitmap bitmap)
- {
- IntPtr hBitmap = bitmap.GetHbitmap();
- System.Windows.Media.ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
- hBitmap,
- IntPtr.Zero,
- System.Windows.Int32Rect.Empty,
- System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
- if (!DeleteObject(hBitmap))//记得要进行内存释放。否则会有内存不足的报错。
- {
- throw new System.ComponentModel.Win32Exception();
- }
-
- return wpfBitmap;
- }
- #endregion
-
- }
- }
- Random rdm = new Random();
- this.image1.Source = FrmClass.BitmapToBitmapSource(AppResource.Vote);
- this.image2.Source = FrmClass.GetImageBrushFrom_PResource(AppResource.Vote).ImageSource;
参考文献:
http://www.wxzzz.com/1410.html