怎么把扫描获得的图片保存到数据库

作者:控件中国网   出处:控件中国网   2015-12-03 15:04:49   阅读:15

Dynamic .NET TWAINDynamic Web TWAIN都是目前比较专业的扫描类控件,前者用于桌面应用程序,后者用于WEB程序,不仅可以轻松从扫描仪获取图片还可以进行各种扫描设置,对扫描后的图片也可以进行处理。
当从扫描仪获取到图片后可以保存到本地也或上传到服务器,也可以保存到各种数据中,这篇文章主要介绍怎么使用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();
}
 
}
}
Copyright© 2006-2015 ComponentCN.com all rights reserved.重庆磐岩科技有限公司(控件中国网) 版权所有 渝ICP备12000264号 法律顾问:元炳律师事务所
客服软件
live chat