1.選擇本地圖片并存進資料庫
2.Save()方法
3.從資料庫讀取照片
最近專案要需要上傳與下載圖片,想了想如何存盤圖片,可以用本地路徑與用二進制資料存盤到資料庫,最后權衡利弊決定將圖片存進資料庫,本文詳細講解了如何將圖片存進SQL資料庫,以及如何從SQL資料庫中讀取圖片,希望大家能夠有所識訓!!!
1.選擇本地圖片并存進資料庫
/// <summary>
/// 將圖片存進資料庫
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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()方法
/// <summary>
/// 存進資料庫
/// </summary>
/// <param name="imgBytesIn">二進制資料</param>
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.從資料庫讀取照片
/// <summary>
/// 從資料庫讀取圖片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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("讀取成功");
}
}
如果本篇博客對您有一定的幫助,大家記得留言+點贊哦,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/205704.html
標籤:java
