2 回答
TA贡献1895条经验 获得超3个赞
根据我的经验,这是一种比至少快四倍的方法CreateBitmapSourceFromHBitmap。
它要求您设置正确PixelFormat的结果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,
bitmap.HorizontalResolution, bitmap.VerticalResolution,
PixelFormats.Bgr24, null,
bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride);
bitmap.UnlockBits(bitmapData);
return bitmapSource;
}
TA贡献1802条经验 获得超6个赞
在克莱门斯回答之前,我回答了自己:
[DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)]
public static extern void CopyMemory(IntPtr dest, IntPtr src, uint count);
WriteableBitmap writeableBitmap = new WriteableBitmap(1280, 1024, 96.0, 96.0, PixelFormats.Bgr24, null);
public MainWindow()
{
InitializeComponent();
ImageTarget.Source = writeableBitmap;
Messenger.Default.Register<Bitmap>(this, (bmp) =>
{
ImageTarget.Dispatcher.BeginInvoke((Action)(() =>
{
BitmapData data = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat);
writeableBitmap.Lock();
CopyMemory(writeableBitmap.BackBuffer, data.Scan0,
(writeableBitmap.BackBufferStride * bmp.Height));
writeableBitmap.AddDirtyRect(new Int32Rect(0, 0, bmp.Width, bmp.Height));
writeableBitmap.Unlock();
bmp.UnlockBits(data);
}));
});
}
现在我的CPU使用率约为15%
- 2 回答
- 0 关注
- 691 浏览
添加回答
举报