当从扫描仪获取到图片后可以保存到本地也或上传到服务器,也可以保存到各种数据中,这篇文章主要介绍怎么使用C#把扫描获取的图片保存到SQL数据库中,本事例中扫描获取的图片保存为D:\picfile.jpg,当然开发人员也可以不保存到本地,直接把获取的图片保存到数据库。
下面是创建数据库表的SQL语句:
CREATE TABLE [dbo].[imgtable](
[id] [int] NULL,
[img] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
具体保存本地图片到数据库的方法如下,如果从扫描仪获取图片直接保存到数据库把代码稍作修改即可:
using System;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Data.SqlClient ;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string fName ;
SqlConnection cnn ;
string connectionString = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
connectionString = "Data Source=servername; Initial Catalog=databasename; User ID=sa; Password=password";
cnn = new SqlConnection(connectionString);
fName = "D:\\picfile.jpg";
if (File.Exists(fName))
{
int id = 2;
byte[] content = ImageToStream(fName);
cnn.Open();
SqlCommand cmd = new SqlCommand("insert into imgtable (id,img) values ( @id,@img)", cnn);
cmd.Parameters.AddWithValue("@id", id);
cmd.Parameters.AddWithValue("@img", content);
cmd.ExecuteNonQuery();
cnn.Close();
MessageBox.Show ("Image inserted");
}
else
{
MessageBox.Show(fName + " not found ");
}
}
private byte[] ImageToStream(string fileName)
{
MemoryStream stream = new MemoryStream();
tryagain:
try
{
Bitmap image = new Bitmap(fileName);
image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception ex)
{
goto tryagain;
}
return stream.ToArray();
}
}
}