C#如何从数据库里读取iamge类型的数据,让其显示在pictureBox里(整理)

来源:互联网 发布:vb软件是什么 编辑:程序博客网 时间:2024/05/30 05:28
wkxgyg的方法:
if (dtZG.Rows[0]["相片"].ToString() != ""){    byte[] bytes = (byte[])dtZG.Rows[0]["相片"];    MemoryStream memStream = new MemoryStream(bytes);    try    {         Bitmap myImage = new Bitmap(memStream);         this.picPhoto.BackgroundImage = myImage;    }    catch (Exception ex)    {         MessageBox.Show("获取照片发生异常:/r/n" + ex.Message, "",MessageBoxButtons.OK, MessageBoxIcon.Error);     } }
mygoda的方法
看到好多类似的帖子..要么求助..要么不说..本人经历过了..虽然方法也是问的别人..但本人不敢独享,,,拿出来和大家分享一下...有点粗糙,,大家谅解..首先..定义一个函数..将图片转化为二进制码//定义将图片转化为长二进制代码的函数getphoto()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;}//这是定义函数..然后..就是将转换成二进制码的图片插入数据库中..下面是简单的也是重要的sql语句..if (this.pictureBox1.Image != null){sql1 = sql1 + ",Photo";sql2 = sql2 + ",bytBLOBData";Byte[] bytBLOBData = getphoto(openFileDialog1.FileName);cmd.Parameters.Add(new OleDbParameter("jpeg", OleDbType.Binary, bytBLOBData.Length, ParameterDirection.Input, true, 0, 0, null, DataRowVersion.Default, bytBLOBData));}接下来..是读取...string sql = "select photo from studentinfo where studentid = " + this.Tag.ToString();OleDbCommand cmd = new OleDbCommand(sql, connection1);if (Convert.DBNull != cmd.ExecuteScalar())pictureBox1.Image = Image.FromStream(new MemoryStream((Byte[])cmd.ExecuteScalar()));//读取长二进制为图片..//////说得很简单..旨在抛砖引玉..希望大家多多讨论...
原创粉丝点击