目录

1.选择本地图片并存进数据库

2.Save()方法

3.从数据库读取照片

最近项目要需要上传与下载图片,想了想如何存储图片,可以用本地路径与用二进制数据存储到数据库。最后权衡利弊决定将图片存进数据库。本文详细讲解了如何将图片存进SQL数据库,以及如何从SQL数据库中读取图片。希望大家能够有所收获!!!

1.选择本地图片并存进数据库

///

/// 将图片存进数据库

///

///

///

private void button2_Click(object sender, EventArgs e)

{

//点击按钮弹出对话框

//选中图片,为Img的属性

OpenFileDialog ofd = new OpenFileDialog(); //打开文件

ofd.Title = "请选择图片文件";//弹出框的标题

ofd.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);//设置系统目录

// ofd.InitialDirectory = @"C:\Users\Administrator\Pictures";//设置系统目录

ofd.Filter = "(*.jpg)|*.jpg";

if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)

{

this.pictureBox1.Image = Image.FromStream(ofd.OpenFile()); //获取当前选择的图片

string path = ofd.FileName.ToString(); //获取当前图片的路径

FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); //将指定路径的图片添加到FileStream类中

BinaryReader br = new BinaryReader(fs);//通过FileStream对象实例化BinaryReader对象

byte[] imgBytesIn = br.ReadBytes(Convert.ToInt32(fs.Length));//将图片转为二进制数据

Save(imgBytesIn);//调用(自己写的一个方法)

}

}

2.Save()方法

///

/// 存进数据库

///

/// 二进制数据

private void Save(byte[] imgBytesIn)

{

try

{ //连接数据库

SqlConnection con = new SqlConnection("server=192.168.111.100;uid=sa;pwd=123456;database=Chargetest");//连接本地数据库

con.Open();

SqlCommand cmd = new SqlCommand("insert into image (Img_url) values(@Image);", con); //SQL语句

cmd.Parameters.Add("@Image", SqlDbType.Image);

cmd.Parameters["@Image"].Value = imgBytesIn;

cmd.ExecuteNonQuery();

con.Close();

MessageBox.Show("图片上传成功");

}

catch

{

MessageBox.Show("您选择的图片不能被读取或文件类型不对!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);

}

}

3.从数据库读取照片

///

/// 从数据库读取图片

///

///

///

private void button1_Click(object sender, EventArgs e)

{

byte[] MyData = new byte[0];

using (SqlConnection conn = new SqlConnection("server=ZYB;Database =Chargetest; User ID = sa;Password =123456"))

{

conn.Open();

SqlCommand cmd = new SqlCommand();

cmd.Connection = conn;

cmd.CommandText = "select * from image where Id=14"; //写自己要查图片的主键

SqlDataReader sdr = cmd.ExecuteReader();

sdr.Read();

object o = sdr["img_url"];

MyData = (byte[])sdr["img_url"];//读取第一个图片的位流

MemoryStream memoryStream = null;

memoryStream = new MemoryStream(MyData);

pictureBox1.Image = Image.FromStream(memoryStream);//将图片赋给pictureBox1控件

MessageBox.Show("读取成功");

}

}

如果本篇博客对您有一定的帮助,大家记得留言+点赞哦。