本文介绍了快速将位图转换为位图源 wpf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在 Image
组件上以 30Hz 的频率绘制图像.我使用此代码:
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;
}));
});
}
问题是,使用这段代码,我的 CPU 使用率大约为 80%,如果没有转换,它大约为 6%.
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) ?
推荐答案
这里有一种方法(根据我的经验)至少比 CreateBitmapSourceFromHBitmap
快四倍.
Here is a method that (to my experience) is at least four times faster than CreateBitmapSourceFromHBitmap
.
它要求您为结果 BitmapSource 设置正确的 PixelFormat
.
It requires that you set the correct PixelFormat
of the resulting BitmapSource.
public static 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,
bitmap.HorizontalResolution, bitmap.VerticalResolution,
PixelFormats.Bgr24, null,
bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride);
bitmap.UnlockBits(bitmapData);
return bitmapSource;
}
这篇关于快速将位图转换为位图源 wpf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!