Creating a BitmapImage WPF

早过忘川 提交于 2019-12-01 06:08:11

问题


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.

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

or alternativly create an ImageSource object from the data?

Thanks,

Eamonn


回答1:


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

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:

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



来源:https://stackoverflow.com/questions/5375943/creating-a-bitmapimage-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!