由于本人做图像自动识别系统,用到模板特征匹配的方法,于是系统自然要存储大量的图像模板,模板要能随时存入、删除与取出,系统完整的代码不方便给出,给个最初编写的存储演示的小程序,其功能界面如下:
代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//coded by langyue_wu@163.com
using System.Data.SqlClient;
using System.IO;
namespace shujuku
{
public partial class Form1 : Form
{ public int i=0;
private string connString="Data Source=BLUESKY//SQLEXPRESS;Initial Catalog=Picture;Integrated Security=True";
SqlConnection conn;
SqlDataAdapter adapter;
DataSet dataset;
public Form1()
{
InitializeComponent();
string sqlstr = "select * from pict";
conn = new SqlConnection(connString);
adapter = new SqlDataAdapter(sqlstr, conn);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.UpdateCommand = builder.GetUpdateCommand();
dataset = new DataSet();
adapter.Fill(dataset, "pict");
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: 这行代码将数据加载到表“pictureDataSet.pict”中。您可以根据需要移动或移除它。
// this.pictTableAdapter.Fill(this.pictureDataSet.pict);
}
private void ShowImage()
{
byte[] bytes = (byte[])dataset.Tables[0].Rows[i][1];
MemoryStream memStream = new MemoryStream(bytes);
try
{
Bitmap myImage = new Bitmap(memStream);
this.pictureBox1.Image = myImage;
}
catch
{
this.pictureBox1.Image = null;
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
adapter.Update(dataset, "pict");
MessageBox.Show("保存成功");
}
private void buttonUpdateImage_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.ShowDialog();
if (openFileDialog1.FileName.Trim()!="")
{
Stream myStream = openFileDialog1.OpenFile();
int length = (int)myStream.Length;
byte[] bytes = new byte[length];
myStream.Read(bytes, 0, length);
myStream.Close();
dataset.Tables[0].Rows[i][1] = bytes;
dataset.Tables[0].Rows[i][0] = textBox1.Text;
ShowImage();
i++;
}
}
private void button1_Click(object sender, EventArgs e)
{
//string strSql = "SELECT count(*) FROM pict where name=" + textBox1.Text;
string strSql = "SELECT * FROM pict where name=" + "'"+textBox1.Text+"'";
conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(strSql, conn);
//打开数据库连接
this.conn.Open();
//执行Sql语句
SqlDataReader MyReader=cmd.ExecuteReader(CommandBehavior.CloseConnection);
MyReader.Read();
MemoryStream MyMemoryStream=new MemoryStream((byte[])MyReader["img"]);
//创建一个 Image 对象,并赋值给 Picture对象的 Image 属性
this.pictureBox1.Image = Image.FromStream(MyMemoryStream);
//关闭内存流
MyMemoryStream.Close();
MyReader.Close();
}
}
}