数据库存取图片信息,有两种方式:
1)转换成二进制数据存储,故首先设置对应的数据字段数据类型为Blob.
2)服务器设置路径保存上传文件,数据库中只存储文件路径。
这里采用第一种方式简单示范如何存储并取出图片。涉及几个类的使用,已经做出简单注释。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Data.OracleClient;//添加引用 namespace ImageDemo { public partial class Form1 : Form { OpenFileDialog filedialog; string connstr = ""; public Form1() { connstr = "Data Source=xxx;user id=xxx;password=xxx"; InitializeComponent(); } /// <summary> /// 获得要上传的文件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { filedialog = new OpenFileDialog(); filedialog.FilterIndex = 1; filedialog.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*"; if (filedialog.ShowDialog() == DialogResult.OK) { txtpath.Text = filedialog.FileName; } } /// <summary> /// 上传到数据库中:往数据库存入图片信息 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; //获得上传图片的二进制信息 byte[] buffer = File.ReadAllBytes(txtpath.Text.Trim()); Random rd = new Random(); string name = rd.Next(999).ToString(); string sql = "insert into ivan_qq_user(id,name,image) values('"+Guid.NewGuid().ToString()+"','"+name+"',:image)"; using (OracleConnection conn = new OracleConnection(connstr)) { conn.Open(); OracleCommand cmd = new OracleCommand(sql, conn); //指名参数类型为Blob cmd.Parameters.Add(":image", OracleType.Blob); cmd.Parameters[":image"].Value = buffer; cmd.ExecuteNonQuery(); } PreviewImage(name); Cursor.Current = Cursors.Default; MessageBox.Show("Done....."); } /// <summary> /// 预览图像信息:从数据库读图片信息 /// </summary> /// <param name="name"></param> private void PreviewImage(string name) { ISDApp01.ISDApp01 isd = new ImageDemo.ISDApp01.ISDApp01(); string sql = "select image from IVAN_QQ_USER where name='"+name+"'"; using (OracleConnection conn = new OracleConnection(connstr)) { conn.Open(); OracleCommand cmd = new OracleCommand(sql,conn); //获得数据信息并转换成二进制 byte[] fileData = cmd.ExecuteScalar() as byte[]; MemoryStream ms = new MemoryStream(fileData); //把二进制信息转换成image并show出 Image image = Image.FromStream(ms); pictureBox1.Image = image; } } } }