private static void copyBitmap(BitmapSource source, WriteableBitmap target, bool dispatcher)
{
int width = source.PixelWidth;
int height = source.PixelHeight;
int stride = width * ((source.Format.BitsPerPixel + 7) / 8);
byte[] bits = new byte[height * stride];
source.CopyPixels(bits, stride, 0);
source = null;
//original code.
//writeBitmap.Dispatcher.Invoke(DispatcherPriority.Background,
// new ThreadStart(delegate
// {
// //UI Thread
// Int32Rect outRect = new Int32Rect(0, (int)(writeBitmap.Height - height) / 2, width, height);
// writeBitmap.WritePixels(outRect, bits, stride, 0);
// }));
//Bugfixes by h32
if (dispatcher)
{
target.Dispatcher.BeginInvoke(DispatcherPriority.Background,
new ThreadStart(delegate
{
//UI Thread
var delta = target.Height - height;
var newWidth = width > target.Width ? (int)target.Width : width;
var newHeight = height > target.Height ? (int)target.Height : height;
Int32Rect outRect = new Int32Rect(0, (int)(delta >= 0 ? delta : 0) / 2, newWidth, newWidth);
try
{
target.WritePixels(outRect, bits, stride, 0);
}
catch (Exception)
{
System.Diagnostics.Debugger.Break();
}
}));
}
else
{
var delta = target.Height - height;
var newWidth = width > target.Width ? (int)target.Width : width;
var newHeight = height > target.Height ? (int)target.Height : height;
Int32Rect outRect = new Int32Rect(0, (int)(delta >= 0 ? delta : 0) / 2, newWidth, newWidth);
try
{
target.WritePixels(outRect, bits, stride, 0);
}
catch (Exception)
{
System.Diagnostics.Debugger.Break();
}
}
}