本實例主要介紹如何將圖片存入數據庫。將圖片存入數據庫,首先要在數據庫中建立一張表,將存儲圖片的字段類型設為Image類型,用FileStream類、BinaryReader把圖片讀成字節的形式,賦給一個字節數組,然后用ADO.SqlCommand對象的ExecuteNonQuery()方法來把數據保存到數據庫中。主要代碼如下:
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "*jpg|*.JPG|*.GIF|*.GIF|*.BMP|*.BMP";
if(openFileDialog1.ShowDialog()==DialogResult.OK)
{
string fullpath =openFileDialog1.FileName;//文件路徑
FileStream fs = new FileStream(fullpath, FileMode.Open);
byte[] imagebytes =new byte[fs.Length];
BinaryReader br = new BinaryReader(fs);
imagebytes = br.ReadBytes(Convert.ToInt32(fs.Length));
//打開數據庫
SqlConnection con = new SqlConnection("server=(local);uid=sa;pwd=;database=db_05");
con.Open();
SqlCommand com = new SqlCommand("insert into tb_08 values(@ImageList)",con);
com.Parameters.Add("ImageList", SqlDbType.Image);
com.Parameters["ImageList"].Value = imagebytes;
com.ExecuteNonQuery();
con.Close();
}
}
本實例主要介紹如何從數據庫中把圖片讀出來。實現本實例主要是利用SqlDataReader從數據庫中把Image字段值讀出來,賦給一個byte[]字節數組,然后使用MemoryStream類與Bitmap把圖片讀取出來。主要代碼如下:
private void button1_Click(object sender, EventArgs e)
{
byte[] imagebytes = null;
//打開數據庫
SqlConnection con = new SqlConnection("server=(local);uid=sa;pwd=;database=db_05");
con.Open();
SqlCommand com = new SqlCommand("select top 1* from tb_09", con);
SqlDataReader dr = com.ExecuteReader();
while (dr.Read())
{
imagebytes = (byte[])dr.GetValue(1);
}
dr.Close();
com.Clone();
con.Close();
MemoryStream ms = new MemoryStream(imagebytes);
Bitmap bmpt = new Bitmap(ms);
pictureBox1.Image = bmpt;
}
本實例主要介紹如何只允許輸入指定圖片格式。用OpenFileDialog控件打開圖片文件,只要將OpenFileDialog控件的Filter屬性指定為特定的圖片格式即可。例如,打開.bmp文件的圖片,主要代碼如下:
this.openFileDialog1.Filter = "bmp文件(*.bmp)|*.bmp";
在用pictureBox控件輸入圖片時,要想統一圖片大小,只需把控件的SizeMode屬性值設為StretchImage即可,StretchImage值表示圖像的大小將調整為控件的大小。這樣,圖片的大小就統一了。