我正在使用A Forge.NET庫製作一個網絡攝像頭與C#,我想打開攝像頭採取rubix立方體圖片。我使用圖片框來處理網絡攝像頭幀,並且我想在圖片框內製作3 * 3的網格。如何網絡攝像頭包圍在網格中使用C#
它的工作原理,但之後的3秒生成異常運行:
g = Graphics.FromImage(videoBox.Image); ----> InvalidOperationException
這裏是我的代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AForge.Video;
using AForge.Video.DirectShow;
namespace WebcamTester
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private FilterInfoCollection webcam;
private VideoCaptureDevice cam;
private Bitmap bit = new Bitmap(640, 480);
private Graphics g;
private int cellsNumber;
private int cellSize;
private void Form1_Load(object sender, EventArgs e)
{
webcam = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo VideoCaptureDevice in webcam)
{
comboBox1.Items.Add(VideoCaptureDevice.Name);
}
comboBox1.SelectedIndex = 0;
cam = new VideoCaptureDevice(webcam[comboBox1.SelectedIndex].MonikerString);
cam.NewFrame += new NewFrameEventHandler(cam_NewFrame);
cam.Start();
}
void cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
bit = (Bitmap)eventArgs.Frame.Clone();
videoBox.Image = bit;
g = Graphics.FromImage(videoBox.Image);
Pen p = new Pen(Color.Black, 2);
cellSize = 100;
cellsNumber = 4;
for (int y = 0; y <= cellsNumber; ++y)
{
g.DrawLine(p, 0, y * cellSize, cellsNumber * cellSize, y * cellSize);
}
for (int x = 0; x <= cellsNumber; ++x)
{
g.DrawLine(p, x * cellSize, 0, x * cellSize, cellsNumber * cellSize);
}
}
private void button2_Click(object sender, EventArgs e)
{
saveFileDialog1.InitialDirectory = @"d:\picture";
cam.Stop();
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
videoBox.Image.Save(saveFileDialog1.FileName);
cam.Start();
}
else
cam.Start();
}
}
}
[你應該總是調用Dispose方法以釋放圖形和由FromImage方法創建的相關資源。] (http://msdn.microsoft.com/en-us/library/system.drawing.graphics.fromimage.aspx) – 2013-02-09 22:51:38
也有可能您從圖像盒創建圖形時收到一幀圖像。嘗試使用本地方法處理所有對象,並僅使用鎖定將結果設置爲ui。 – 2013-02-09 22:55:26