Necesito dibujar una imagen en el componente Image
a 30 Hz. Yo uso este código:
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; })); }); }
El problema es que, con este código, el uso de mi CPU es de alrededor del 80 % y, sin la conversión, es de alrededor del 6 %.
Entonces, ¿por qué la conversión de mapa de bits es tan larga?
¿Existe un método más rápido (con código inseguro)?
Aquí hay un método que (según mi experiencia) es al menos cuatro veces más rápido que CreateBitmapSourceFromHBitmap
.
Requiere que establezca el PixelFormat correcto del PixelFormat
resultante.
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; }
Me respondí a mí mismo antes de que Clemens respondiera con:
[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); })); }); }
Ahora mi uso de CPU es de alrededor del 15%