我有一些定时器,耗时180〜200 ms。 如果计时器已过去,则创建字节数组(大小为3840 * 1250)并生成事件。 然后,事件接收器将创建位图并将图像更新为图片框。 但是,我的方法中有一个致命的致命执行引擎错误(CreateBitmapFromByteSource(w,h,source)。
当BitmapEncoder调用Save方法时发生异常。
请帮助我...
计时器经过的身体
private void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
System.Threading.Thread tr = new System.Threading.Thread(() =>
{
int trID = System.Threading.Thread.CurrentThread.ManagedThreadId;
byte[] source1 = BitmapUtilities.GenerateSourceData(this._sourceDataLength);
byte[] srouce2 = BitmapUtilities.GenerateSourceData(this._sourceDataLength);
if (UpdateSourceData != null)
UpdateSourceData(this, new ImageGenerateEventArgs(Count, this._width, this._height, source1, srouce2));
});
tr.IsBackground = true;
tr.Start();
}
事件接收器主体
private void ImageViewer_UpdateSourceData(object sender, ImageGenerateEventArgs args)
{
Action lambda = () =>
{
int trID = System.Threading.Thread.CurrentThread.ManagedThreadId;
Bitmap bitmap = BitmapUtilities.CreateBitmapFromByteSource(args.W, args.H, args.S1);
bitmap.RotateFlip(RotateFlipType.Rotate180FlipX);
if (this.pictureBox1.Image != null)
this.pictureBox1.Image.Dispose();
this.pictureBox1.Image = bitmap;
this.pictureBox1.Update();
bitmap.Dispose();
bitmap = BitmapUtilities.CreateBitmapFromByteSource(args.W, args.H, args.S2);
bitmap.RotateFlip(RotateFlipType.Rotate180FlipX);
if (this.pictureBox2.Image != null)
this.pictureBox2.Image.Dispose();
this.pictureBox2.Image = bitmap;
this.pictureBox2.Update();
bitmap.Dispose();
};
if (this.InvokeRequired)
this.Invoke(lambda);
else
lambda();
}
CreateBitmapFromByteSource(w,h,source)正文
static public Bitmap CreateBitmapFromByteSource(int width, int height, byte[] byteSource)
{
Bitmap image;
BitmapSource src;
try
{
src = BitmapSource.Create(width, height, 96, 96, System.Windows.Media.PixelFormats.Gray8, null, byteSource, width);
using (MemoryStream ms = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(src));
enc.Save(ms);
image = new System.Drawing.Bitmap(ms);
}
return image;
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
return null;
}
}