简体   繁体   English

创建BitmapImage WPF

[英]Creating a BitmapImage WPF

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 [],当我创建一个Windows.System.Drawing.Bitmap,并将其转换为BitmapImage时,这感觉就像一个缓慢无助的方式来做到这一点。

Does anyone what the fastest way to create a BitmapImage of a ushort[] is? 有没有人创建ushort []的BitmapImage的最快方法是什么?

or alternativly create an ImageSource object from the data? 或者从数据中另外创建一个ImageSource对象?

Thanks, 谢谢,

Eamonn 埃蒙·

My previous method for converting Bitmap to BitmapImage was: 我之前将Bitmap转换为BitmapImage的方法是:

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());

EDIT: 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: 编辑:任何人使用这个应该知道bitmap.GetHbitmap创建一个非托管对象,因为这是非托管的,它不会被.net垃圾收集器拾取,必须删除以避免内存泄漏,使用以下代码来解决这个问题:

    [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);
    }

(its not very neat having to import a dll like like but this was taken from msdn, and seems to be the only way around this issue - http://msdn.microsoft.com/en-us/library/1dz311e4.aspx ) (它不是很整齐,必须导入像这样的DLL,但这是从msdn,并似乎是围绕这个问题的唯一方法 - http://msdn.microsoft.com/en-us/library/1dz311e4.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM