【发布时间】:2019-03-31 21:07:55
【问题描述】:
我想在 BitmapSource 上绘图。
我的帧源来自位图类型的网络摄像头。我将其转换为 BitmapSource,绘制一个矩形并设置为带有数据绑定的 Image 控件源。
//convert Bitmap to BitmapSource:
//WinForms -> WPF
public BitmapSource BitmapToBitmapSource(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;
}
//Drawing code:
public static BitmapSource DrawRect(BitmapSource frame)
{
RenderTargetBitmap rtb = new RenderTargetBitmap(frame.PixelWidth, frame.PixelHeight, frame.DpiX, frame.DpiY, PixelFormats.Pbgra32);
DrawingVisual dv = new DrawingVisual();
using (DrawingContext dc = dv.RenderOpen())
{
dc.DrawImage(frame, new Rect(0, 0, frame.Width, frame.Height));
//dc.DrawLine(new Pen(Brushes.White, 1), new Point(0, 0), new Point(frame.Width, frame.Height));
dc.DrawRectangle(null, new Pen(Brushes.Red, 1), new Rect(50, 50, 100, 100));
}
rtb.Render(dv);
rtb.Freeze();
return rtb;
}
我的硬件使用结果:
CPU:24% 显卡:5.4%
在英特尔酷睿 i7-4900MQ @ 2.8Ghz 上; 4核; 8线程 / NVIDIA Quadro K2100M
结果视频不流畅,有点慢。
有人知道我怎样才能最快吗?
【问题讨论】: