public Byte[] getphoto(string photopath)
{
string str = photopath;
FileStream file = new FileStream(str, FileMode.Open, FileAccess.Read);
Byte[] bytBLOBData = new Byte[file.Length];
file.Read(bytBLOBData, 0, bytBLOBData.Length);
file.Close();
return bytBLOBData;
}
//这是定义函数..
private void button1_Click(object sender, EventArgs e)
{
//然后..就是将转换成二进制码的图片插入数据库中..下面是简单的也是重要的sql语句..
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.ShowDialog();
Byte[]bytBLOBData = getphoto(openFileDialog1.FileName);
string pic = string.Join("",bytBLOBData);
string sql = string.Format("insert UserImages select '{0}'",pic);
open();
SqlCommand cmd = new SqlCommand(sql,conn);
cmd.ExecuteNonQuery();
//cmd.Parameters.Add(new SqlParameter("jpeg", SqlDbType.Binary, bytBLOBData.Length, ParameterDirection.Input, true, 0, 0, null, DataRowVersion.Default, bytBLOBData));
close();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
//接下来..是读取...
string sql = "select image from UserImages";
open();
SqlCommand cmd = new SqlCommand(sql, conn);
char[]o = cmd.ExecuteScalar().ToString().ToArray();
//if (Convert.DBNull != cmd.ExecuteScalar())
pictureBox1.Image = Image.FromStream(new MemoryStream((Byte[])cmd.ExecuteScalar()));//读取长二进制为图片..
close();
}
转换的时候说丛书无效 请前辈们帮我看看
10 个解决方案
插入感觉就不对。为什么不用SqlParameter?
byte[] b= (byte[])dataReader[0];
if (b.Length>0)
{
MemoryStream stream = new MemoryStream(b, true);
stream.Write(b, 0, b.Length);
pictureBox1.Image = new Bitmap(stream);
stream.Close();
}
检查字节长度,保存时是否正确
void insertSQL(byte[] Image)
{
string ConStr = "server=(local);user id=sa;pwd=sa;database=test";
SqlConnection conn = new SqlConnection(ConStr);
string strSql = "Insert into piclist(pic) values(@pic)";
SqlCommand cmd = new SqlCommand(strSql, conn);
cmd.Parameters.Add("@pic", SqlDbType.Image);
cmd.Parameters["@pic"].Value = Image;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
FileStream fs = new FileStream(@"E:\20.jpg", FileMode.Open);
int le=Convert.ToInt32(fs.Length);
byte[] ib = new byte[le];
fs.Read(ib,0,le);
fs.Close();
insertSQL(ib);
}
这是插入
void SelectSQL()
{
string ConnStr = "server=(local);user id=sa;pwd=sa;database=test";
string strSql = "select * from piclist";
SqlConnection conn = new SqlConnection(ConnStr);
conn.Open();
SqlCommand cmd = new SqlCommand(strSql, conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
byte[] b = (Byte[])reader["pic"];
FileStream fs = new FileStream(@"E:\123.jpg", FileMode.CreateNew);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(b, 0, b.Length);
}
reader.Close();
conn.Close();
}
这是读取
就是存取二进制数据还是存取图片路径,都不怎么麻烦吧...