WPF Bitmap转imagesource


因为WPF中不支持直接显示bitmap格式图片,因此需要对bitmap转换成imagesource再显示。

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

public static ImageSource ChangeBitmapToImageSource(Bitmap bitmap)
{
    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;
}

需要及时释放hBitmap,否则内存会很快占满。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM