C#WinForm中,用于将图片以二进制存入sql数据库中,并将图片从数据库中取出,显示在PictureBox控件中。

2024-11-18 11:33:05
推荐回答(3个)
回答(1):

插入: //单击图片选择添加的图片 private void pic_Click(object sender, EventArgs e)
{ dlg.Filter = "JPG|*.jpg|BMP|*.bmp|PNG|*.png";
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
pic.Image = Image.FromFile(dlg.FileName);
txtFilePath = dlg.FileName;
}
} public byte[] picData; public string txtFilePath = ""; 添加确定按钮代码: f (txtFilePath != "")
{
try
{
FileStream fs = new FileStream(txtFilePath, FileMode.Open, FileAccess.Read);
int len = Convert.ToInt32(fs.Length);
b = new byte[len];
fs.Read(b, 0, len);
fs.Close();
}
catch
{
b = null;
}
} SqlConnection conn = new SqlConnection(strConn);
conn.Open(); SqllCommand cmdInsert = new SqlCommand();
cmdInsert.Connection = conn;
cmdInsert.CommandText =插入语句; cmdInsert.Parameters.Add("@照片", SqlDbType.Image); if (txtFilePath == "")
{
cmdInsert.Parameters["@照片"].Value = DBNull.Value;
}
else
{
cmdInsert.Parameters["@照片"].Value = b;
}
cmdInsert.ExecuteNonQuery();
conn.Close();获取: public byte[] picData; SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from 联系人 where 编号=" + ID.ToString();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet(); sda.Fill(ds); if (ds.Tables[0].Rows.Count == 1)
{
if (ds.Tables[0].Rows[0]["照片"] == DBNull.Value)
{ //pic为picturebox控件
pic.Image = PhoneBoook.Properties.Resources.DeskShade;//为空的话给个默认图片
}
else
{
byte[] b = (byte[])(ds.Tables[0].Rows[0]["照片"]);
pic.Image = Image.FromStream(new MemoryStream(b));
picData = b;
}
}

回答(2):

首先把图片转化成2进制流
Image _Image = Image.FromFile(@"C:\1.jpg");
System.IO.MemoryStream _ImageMem = new System.IO.MemoryStream();
_Image.Save(_ImageMem, ImageFormat.Bmp);
byte[] _ImageBytes = _ImageMem.GetBuffer();
然后同样的方法放入数据库
SqlCommand _SqlCommand = new SqlCommand("Insert into ImageTable(name,image)values(@name,@image)");
_SqlCommand.Parameters.Add(new SqlParameter("@name", SqlDbType.VarChar, 20));
_SqlCommand.Parameters.Add(new SqlParameter("@image", SqlDbType.Image));

_SqlCommand.Parameters[0].Value = "ImageName";
_SqlCommand.Parameters[1].Value = _ImageBytes;
执行这个SQLCOMMAND
读出的时候相反

具体的 代码:

//保存图片:
SqlConnection conn = new SqlConnection(@"data source=.;uid=sa;pwd=;database=master"); conn.Open();
SqlCommand cmd = new SqlCommand("insert into image values(@i)", conn);
byte[] ib = new byte[60000];
FileStream fs = new FileStream(this.openFileDialog1.FileName.ToString(), FileMode.Open, FileAccess.Read); fs.Read(ib, 0, 60000);
cmd.Parameters.Add("@i", SqlDbType.Image, (int)fs.Length);
cmd.Parameters["@i"].Value = ib;
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("保存成功"); /
/显示图片:
SqlConnection conn = new SqlConnection(@"data source=.;uid=sa;pwd=;database=master"); conn.Open();
SqlCommand cmd = new SqlCommand("select image1 from image", conn);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
while (reader.Read())
{ for (int i = 0; i < reader.FieldCount; i++)
{ MemoryStream buf = new MemoryStream((byte[])reader[i]); I
mage image = Image.FromStream(buf,true);
this.pictureBox1.Image = image;
}
}

回答(3):

创建一张测试表(sqlserver2000)
create table [pictable] (
[id] [int] identity (1, 1) not null ,
[img] [image] not null
) on [primary] textimage_on [primary]
go
1,插入数据库的方法(sqlserver2000)this.getConnection() 为获得连接的方法.
public void insertPic(String path)...{
Connection con = this.getConnection();
String sql = "insert into picTable values(?)" ;
try ...{
PreparedStatement pstm = con.prepareStatement(sql);
InputStream is = new FileInputStream(path);

pstm.setBinaryStream(1, is, is.available());
int count = pstm.executeUpdate();
if(count>0)...{
System.out.println("插入成功");
}else...{
System.out.println("插入失败");
}
is.close();
pstm.close();
con.close();

} catch (Exception e) ...{
e.printStackTrace();
}
}2,从数据库中读出来的方法.(sqlserver2000)
public void readPic(int id)...{
Connection con = this.getConnection();
String sql = "select * from picTable where id=?" ;
try ...{
PreparedStatement pstm = con.prepareStatement(sql);
pstm.setInt(1, id);
ResultSet rs = pstm.executeQuery();
rs.next();
InputStream is = rs.getBinaryStream(2);

OutputStream os = new FileOutputStream("f:/temp.jpg");
byte[] buff = new byte[1024];
int len = is.read(buff);
while( len !=-1 )...{
os.write(buff);
len = is.read(buff);
}
System.out.println("写入成功");
is.close();
os.close();
pstm.close();
con.close();
} catch (Exception e) ...{
e.printStackTrace();
}
}