快速转换位图的BitmapSource的WPF [英] fast converting Bitmap to BitmapSource wpf
本文介绍了快速转换位图的BitmapSource的WPF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在图片
组件以30Hz绘制图像。
我用这个code:
公共主窗口()
{
的InitializeComponent(); Messenger.Default.Register<&位图GT;(这一点,(BMP)=>
{
ImageTarget.Dispatcher.BeginInvoke((动作)(()=>
{
VAR HBITMAP = bmp.GetHbitmap();
VAR绘制= System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
HBITMAP,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
DeleteObject的(HBITMAP);
ImageTarget.Source =绘制;
}));
});
}
的问题是,与此code,我的CPU使用率是80%左右,并且,如果没有皈依它是约6%。
那么,为什么转换位图是这么久?结果
有没有更快的方法(不安全code)?
解决方案
下面是(我的经验)比 CreateBitmapSourceFromHBitmap
。<至少快四倍的方法/ p>
它需要你设置正确的结果的BitmapSource。
的的PixelFormat
公开的BitmapSource转换(System.Drawing.Bitmap位图)
{
VAR的位图数据= bitmap.LockBits(
新System.Drawing.Rectangle(0,0,bitmap.Width,bitmap.Height),
System.Drawing.Imaging.ImageLockMode.ReadOnly,bitmap.PixelFormat); VAR的BitmapSource = BitmapSource.Create(
bitmapData.Width,bitmapData.Height,96,96,PixelFormats.Bgr24,空,
bitmapData.Scan0,bitmapData.Stride * bitmapData.Height,bitmapData.Stride); bitmap.UnlockBits(位图数据);
返回的BitmapSource;
}
I need to draw an image on the Image
component at 30Hz.
I use this code :
public MainWindow()
{
InitializeComponent();
Messenger.Default.Register<Bitmap>(this, (bmp) =>
{
ImageTarget.Dispatcher.BeginInvoke((Action)(() =>
{
var hBitmap = bmp.GetHbitmap();
var drawable = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
DeleteObject(hBitmap);
ImageTarget.Source = drawable;
}));
});
}
The problem is, with this code, My CPU usage is about 80%, and, without the convertion it's about 6%.
So why converting bitmap is so long ?
Are there faster method (with unsafe code) ?
解决方案
Here is a method that (to my experience) is at least four times faster than CreateBitmapSourceFromHBitmap
.
It requires that you set the correct PixelFormat
of the resulting BitmapSource.
public BitmapSource Convert(System.Drawing.Bitmap bitmap)
{
var bitmapData = bitmap.LockBits(
new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat);
var bitmapSource = BitmapSource.Create(
bitmapData.Width, bitmapData.Height, 96, 96, PixelFormats.Bgr24, null,
bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride);
bitmap.UnlockBits(bitmapData);
return bitmapSource;
}
这篇关于快速转换位图的BitmapSource的WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文