以二进制形式存取图片
注:此图片表中类型为 text、ntext、image格式才可存入数据库
/// <summary>
/// 以二进制形式存取图片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
try
{
this.pictureBox1.Image = Image.FromStream(this.openFileDialog1.OpenFile());
string str = openFileDialog1.FileName.ToString();
//将指定路径的文件添加到FileStream类中
FileStream fs = new FileStream(str, FileMode.Open, FileAccess.Read);
//通过FileStream类对象实例化BinaryReader类
BinaryReader br = new BinaryReader(fs);
//通过BinaryReader类对象的ReadBytes()方法将FileStream类对象转化为二进制数组
imgBytesIn = br.ReadBytes((int)fs.Length);
//MessageBox.Show(imgBytesIn.ToString());
}
catch
{
MessageBox.Show("您选择的图片不能被读取或文件类型不对!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
this.pictureBox1.Image = null;
}
}
string tablename = "cpic";
private void btAddPic_Click(object sender, EventArgs e)
{
//new Db().InsertInfo_Clpic(cph, imgBytesIn);
if (this.pictureBox1.Image == null)
{
return;
}
new Db().InsertInfo_Clpic(tablename,cph, imgBytesIn);
new Db().CloseConnection();
btAddPic.Enabled = false;
MessageBox.Show("添加成功!");
btUpPic.Enabled = true;
btDelPic.Enabled = true;
}