使用Aforge保存图像

时间:2013-04-04 06:16:12

标签: c# aforge

我写了一个访问网络摄像头的代码,然后单击,将图片保存到文件夹。

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.Imaging;
using AForge.Imaging.Filters;
using AForge.Video;
using AForge.Video.DirectShow;

namespace cam
{
public partial class Form1 : Form
{
    public static Bitmap _latestFrame;
    public Form1()
    {
        InitializeComponent();
    }
    private FilterInfoCollection webcam;
    private VideoCaptureDevice cam;
    Bitmap bitmap;

    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;
      }

    private void button1_Click(object sender, EventArgs e)
    {
        cam = new VideoCaptureDevice(webcam[comboBox1.SelectedIndex].MonikerString);
        cam.NewFrame += new NewFrameEventHandler(cam_NewFrame);
        cam.Start();

    }
    void cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
    {
        bitmap = (Bitmap)eventArgs.Frame.Clone();

        pictureBox1.Image = bitmap;
    }
    private void pictureBox1_Click(object sender, EventArgs e)
    {
        pictureBox1.Image = bitmap;
    }
    private void button3_Click(object sender, EventArgs e)
    {
        if (cam.IsRunning)
        {
            cam.Stop();
        }

    }

    private void button2_Click(object sender, EventArgs e)
    {
        Bitmap current = (Bitmap)_latestFrame.Clone();
        string ActiveDir = AppDomain.CurrentDomain.BaseDirectory;
        string filepath = System.IO.Path.Combine(ActiveDir, @"D://picture/");
        if (!System.IO.Directory.Exists(filepath))
        {
            System.IO.DirectoryInfo OutputDir = System.IO.Directory.CreateDirectory(filepath);
            string fileName = System.IO.Path.Combine(filepath, @"name.bmp");
            if (!System.IO.File.Exists(fileName))
            {
                current.Save(fileName);
            }
        }
        current.Dispose(); 
    }

    }

    }

在button2中,我编写了保存图片的代码,在构建程序时,显示给定行的空引用异常(Bitmap current = (Bitmap)_latestFrame.Clone();

1 个答案:

答案 0 :(得分:1)

就我在代码中看到的而言,新的图像框架被复制到您的成员变量bitmap。似乎永远不会分配静态成员_latestFrame

因此,在button2_Click方法中,将第一行更改为:

Bitmap current = (Bitmap)bitmap.Clone();

现在,如果您在单击按钮时从网络摄像头收到至少一个帧,则应正确保存该帧。

我还认为您在filepath方法中过度处理button2_Click设置。首先,只需将button2_Click方法更改为以下内容,验证图片是否可以正确保存到活动目录:

private void button2_Click(object sender, EventArgs e)
{
    Bitmap current = (Bitmap)bitmap.Clone();
    string filepath = Environment.CurrentDirectory;
    string fileName = System.IO.Path.Combine(filepath, @"name.bmp");
    current.Save(fileName);
    current.Dispose();
}

这将确保每次单击 Capture 按钮时都会将新图像写入“当前目录”。

我已经使用上述更改测试了您的代码,并且它可以完美运行。