Reputation: 520
I am getting Sequence of images from USB and with each image grabbed I convert grabbed result to System.Drawing.Bitmap and after that I convert it to System.Windows.Mesia.Imging.BitmapImage to be able to assign it to Imagesource and finally update UI in dispatcher thread, all this process takes time and it doesn't go live, the sample codes of the camera company (Basler) has used C# and directly assigns System.Drawing.Bitmap to picture box and can show live view without delay. What is the best solution to handle it ? it worth mentioning that with 2048*2000 pixel size the frame rate is almost 50 fps
PixelDataConverter converter = new PixelDataConverter();
Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
converter.OutputPixelFormat = PixelType.BGRA8packed;
IntPtr ptrBmp = bmpData.Scan0;
converter.Convert(ptrBmp, bmpData.Stride * bitmap.Height, grabResult);
bitmap.UnlockBits(bmpData);
BitmapImage bitmapimage = new BitmapImage();
using (MemoryStream memory = new MemoryStream())
{
bitmap.Save(memory, ImageFormat.Bmp);
memory.Position = 0;
bitmapimage.BeginInit();
bitmapimage.StreamSource = memory;
bitmapimage.CacheOption = BitmapCacheOption.OnLoad;
bitmapimage.EndInit();
bitmapimage.Freeze();
}
Dispatcher.Invoke(new Action(() =>
{
imgMain.Source = bitmapimage;
}));
And this is the sample code for c# by company :
Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
// Lock the bits of the bitmap.
BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
// Place the pointer to the buffer of the bitmap.
converter.OutputPixelFormat = PixelType.BGRA8packed;
IntPtr ptrBmp = bmpData.Scan0;
converter.Convert(ptrBmp, bmpData.Stride * bitmap.Height, grabResult); //Exception handling TODO
bitmap.UnlockBits(bmpData);
// Assign a temporary variable to dispose the bitmap after assigning the new bitmap to the display control.
Bitmap bitmapOld = pictureBox.Image as Bitmap;
// Provide the display control with the new bitmap. This action automatically updates the display.
pictureBox.Image = bitmap;
if (bitmapOld != null)
{
// Dispose the bitmap.
bitmapOld.Dispose();
}
}
enter code here
Upvotes: 1
Views: 1310
Reputation: 2889
Use Dispatcher.BeginInvoke instead of Dispatcher.Invoke(...
to set the image asynchronous.
Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() =>
{
imgMain.Source = bitmapimage;
}));
Upvotes: 1