【WPF】Bitmap转为Image控件Source效率,内存释放问题?
背景:做了一个WPF程序,其中有一个Image的控件。通过相机采集实时图像(20帧左右),并返回给WPF程序一个Bitmap图像,通过Image控件来显示。
细节问题:我在WPF程序中定义了一个Timer,基本上也是一秒钟执行20多次,用来刷新Image中的图像,但是Image.Source不能够直接用Bitmap,所以在这里需要将其转换。
我在网上找了很多种方法,虽然能够实现,但是在效率和释放内存上面不能够兼顾。
代码如下:
主程序中的生成Bitmap
System.Drawing.Bitmap bmp = ImageAndBytes.ToGrayBitmap(ImageAndCurveSwitcherRecieveByte, ImageParmterSetting.ImageWidth, ImageParmterSetting.ImageHeight, 500 + ImageParmterSetting.ImageWidth * ImageParmterSetting.ImageHeight * i);
Image.Source = BitmapToBitmapSourceHelper.BitmapToBitmapSourceHelper.BitmapToBitmapSource(bmp);
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
public static IntPtr ptr;
public static System.Windows.Media.Imaging.BitmapSource result;
public static System.Windows.Media.Imaging.BitmapSource BitmapToBitmapSource(System.Drawing.Bitmap bitmap)
{
ptr = bitmap.GetHbitmap();
result = null;
result = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
ptr, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
//release resource
DeleteObject(ptr);
return result;
}
public static BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
{
BitmapImage bitmapImage = new BitmapImage();
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
bitmap.Save(ms, bitmap.RawFormat);
bitmapImage.BeginInit();
bitmapImage.StreamSource = ms;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze();
}
return bitmapImage;
}
public static ImageSource ChangeBitmapToImageSource(Bitmap bitmap)
{
//Bitmap bitmap = icon.ToBitmap();
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;
}
if (TimerTimes > 29) GC.Collect(); TimerTimes = 0;