c#form+mysql储存读取图片_C#从SQL server数据库中读取l图片和存入图片
本實例主要介紹如何將圖片存入數(shù)據(jù)庫。將圖片存入數(shù)據(jù)庫,首先要在數(shù)據(jù)庫中建立一張表,將存儲圖片的字段類型設(shè)為Image類型,用FileStream類、BinaryReader把圖片讀成字節(jié)的形式,賦給一個字節(jié)數(shù)組,然后用ADO.SqlCommand對象的ExecuteNonQuery()方法來把數(shù)據(jù)保存到數(shù)據(jù)庫中。主要代碼如下:
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));
//打開數(shù)據(jù)庫
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();
}
}
本實例主要介紹如何從數(shù)據(jù)庫中把圖片讀出來。實現(xiàn)本實例主要是利用SqlDataReader從數(shù)據(jù)庫中把Image字段值讀出來,賦給一個byte[]字節(jié)數(shù)組,然后使用MemoryStream類與Bitmap把圖片讀取出來。主要代碼如下:
private void button1_Click(object sender, EventArgs e)
{
byte[] imagebytes = null;
//打開數(shù)據(jù)庫
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控件輸入圖片時,要想統(tǒng)一圖片大小,只需把控件的SizeMode屬性值設(shè)為StretchImage即可,StretchImage值表示圖像的大小將調(diào)整為控件的大小。這樣,圖片的大小就統(tǒng)一了。
總結(jié)
以上是生活随笔為你收集整理的c#form+mysql储存读取图片_C#从SQL server数据库中读取l图片和存入图片的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python自定义colorbar_py
- 下一篇: 潜力的监控mysql_Grafana 数