在開發的過程中,難免遇到圖檔儲存問題,解決的方法有很多,這裡我把圖檔以二進制的形式儲存到資料庫中,也許這個形式并不是最高效的方式,但也不失為一種好的方法吧.呵呵,下面簡單的demo可以作為參考:
//單擊"浏覽"按鈕
private void button1_Click(object sender, System.EventArgs e)
{
DialogResult result=this.openFileDialog1.ShowDialog();
if(result==DialogResult.OK)
{
this.textBox1.Text=this.openFileDialog1.FileName.ToString
();
Image img = Bitmap.FromFile(this.textBox1.Text);
this.pictureBox1.Image=img;
}
}
//單擊"确定"按鈕
private void button2_Click(object sender, System.EventArgs e)
{
//插入資料庫操作,圖檔類型的參數為PicToBinary()傳回的byte[]即可
把圖檔以位元組的形式儲存到資料庫中
}
//圖檔轉換為位元組數組
private byte[] PicToBinary()
{
//建立參數集
string path = this.textBox1.Text.Trim();
byte[] source = null;
if(!path.Equals("") && File.Exists(path))
{
FileStream fs=new FileStream
(path,FileMode.Open,FileAccess.Read);//建立檔案流
source=new byte[(int)fs.Length];
fs.Read(source,0,(int)fs.Length);
Image img = Bitmap.FromStream(fs);//把檔案流轉換為圖檔
if(img.Width > 300 || img.Height > 400)
{
MessageBox.Show("圖檔過大,請上傳400*300以下的圖檔");
return;
}
fs.Flush();
fs.Close();
}
return source;
}