下面是 ACCESS 的示例,SQL Server 你需要调整一下。字段类型可以设置为Binary(max) 或 image
-
///
-
///C#以二进制方式存储图片到access数据库中
-
///将指定的图片信息存入到 Access 数据库
-
///
-
///图片名
-
///图片的 Byte
-
public void InsertImageToAccess(String fImageName, Byte[] fImageBinary)
-
{
-
// Access 表// 字段// ImageName 文本// ImageBinary OLE 对象
-
using(OleDbConnection conn =newOleDbConnection(“Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\X.mdb”)){
-
OleDbCommand fInsertCommand =newOleDbCommand();
-
fInsertCommand.Connection = conn;
-
fInsertCommand.CommandText =”INSERT INTO Images (ImageName, ImageBinary) values (?, ?)”;
-
fInsertCommand.Parameters.Add(“@ImageName”, OleDbType.VarChar).Value = fImageName;
-
fInsertCommand.Parameters.Add(“@ImageBinary”, OleDbType.Binary, fImageBinary.Length).Value = fImageBinary;
-
conn.Open();
-
fInsertCommand.ExecuteNonQuery();
-
}
-
}
-
-
///
-
///获取指定图片名的 Byte
-
///
-
///图片名
-
///
-
public Byte[] GetImageFromAccess(String fImageName)
-
{
-
using(OleDbConnection conn =newOleDbConnection(“Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\X.mdb”)){
-
OleDbCommand fSelectCommand =newOleDbCommand();
-
fSelectCommand.Connection = conn;
-
fSelectCommand.CommandText =”SELECT ImageBinary FROM Images WHERE ImageName = ?”;
-
fSelectCommand.Parameters.Add(“@ImageName”, OleDbType.VarChar).Value = fImageName; conn.Open();
-
object o = fSelectCommand.ExecuteScalar();
-
return(o ==null?null: (Byte[])o);
-
}
-
}
-
-
private void button1_Click(objectsender, EventArgs e){
-
using(OpenFileDialog dialog =newOpenFileDialog()){
-
dialog.Filter =”gif|*.gif”;
-
dialog.Multiselect =false;
-
if(dialog.ShowDialog() == DialogResult.OK){
-
stringfImageName = Path.GetFileNameWithoutExtension(dialog.FileName);
-
FileStream fs =newFileStream(dialog.FileName, FileMode.Open, FileAccess.Read);
-
BinaryReader br =newBinaryReader(fs);
-
byte[] fInputImageBinary = br.ReadBytes((int)fs.Length);
-
br.Close();
-
fs.Close();
-
// 保存到数据库
-
this.InsertImageToAccess(fImageName, fInputImageBinary);
-
// 从数据库获取图片并显示到 pictureBox1
-
Byte[] fOutputImageBinary =this.GetImageFromAccess(fImageName);
-
MemoryStream ms =newMemoryStream(fOutputImageBinary);
-
pictureBox1.Image = Image.FromStream(ms);
-
}
-
}
-
}
阅读(2064) | 评论(0) | 转发(0) |