本文介绍了创建一个BitmapImage的WPF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我需要在屏幕上显示,在一分钟我创建一个Windows.System.Drawing.Bitmap,并把它转换为BitmapImage的一个USHORT []包含图像数据,但这种感觉就像一个缓慢inneficent的方式做这一点。

I have a ushort[] containing image data I need to display on screen, at the minute I am creating a Windows.System.Drawing.Bitmap, and converting this to a BitmapImage but this feels like a slow inneficent way to do this.

有没有人有什么最快的方法来创建一个USHORT的BitmapImage的[]是?

Does anyone what the fastest way to create a BitmapImage of a ushort[] is?

或alternativly从数据创建的ImageSource对象?

or alternativly create an ImageSource object from the data?

谢谢

埃蒙·

推荐答案

我的previous方法转换位图的BitmapImage是:

My previous method for converting Bitmap to BitmapImage was:

MemoryStream ms = new MemoryStream(); 
bitmap.Save(ms, ImageFormat.Png); 
ms.Position = 0; 
BitmapImage bi = new BitmapImage(); 
bi.BeginInit(); 
bi.StreamSource = ms; 
bi.EndInit();

我可以使用,以加速这一过程。

I was able to speed it up using

Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), 
                                      IntPtr.Zero, 
                                      Int32Rect.Empty,
                                      System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());

编辑:使用此应该知道,bitmap.GetHbitmap创建一个非托管对象躺在身边,因为这是不受管理它不会被拾起由.NET垃圾收集器,并且必须被删除,以避免内存泄漏的人,请使用以下code解决这样的:

anyone using this should know that bitmap.GetHbitmap creates an unmanaged object lying around, since this is unmanaged it wont be picked up by the .net garbage collector and must be deleted to avoid a memory leak, use the following code to solve this:

    [System.Runtime.InteropServices.DllImport("gdi32.dll")]
    public static extern bool DeleteObject(IntPtr hObject);

    IntPtr hBitmap = bitmap.GetHbitmap();
    try
    {
        imageSource = Imaging.CreateBitmapSourceFromHBitmap(hBitmap,
                                                            IntPtr.Zero,
                                                            Int32Rect.Empty,
                                                            System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
    }
    catch (Exception e) { }
    finally
    {
        DeleteObject(hBitmap);
    }

(它不是很整齐不必导入像像一个DLL,但是这是从MSDN,似乎是解决这个问题的唯一途径 - 的)

这篇关于创建一个BitmapImage的WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 21:48