[英]how to webcam surrounded by a grid using in c#
我正在使用A Forge.NET庫使用c#制作網絡攝像頭,我想打開網絡攝像頭以拍攝rubix立方體圖片。 我使用一個圖片框來處理網絡攝像頭框架,我想在圖片框內制作一個3 * 3的網格。
它可以工作,但運行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();
}
}
}
此異常與“對象當前正在其他地方使用”有關。也許是因為未發布...
你應該試試:
(...)
for (int x = 0; x <= cellsNumber; ++x)
{
g.DrawLine(p, x * cellSize, 0, x * cellSize, cellsNumber * cellSize);
}
g.Dispose();
}
如果這樣做沒有幫助,則應嘗試使用
private object Lock = new object();
lock (Lock) {
using (var 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);
}
g.Dispose();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.