using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
namespace WindowsApplication2
{
public partial class Form1 : Form
{
string photoPath;
SqlConnection sqlCon;
public Form1()
{
InitializeComponent();
sqlCon = new SqlConnection(@"Data Source=.;Initial Catalog=学生党员信息管理系统;Integrated Security=True");
}
#region[定义一个方法显示图片]
private void showImageFromFile(PictureBox sendPictureBox)
{
OpenFileDialog photoFile = new OpenFileDialog();
photoFile.Filter = "(JPEG格式文件)*.jpg|*.jpg";
if (photoFile.ShowDialog() == DialogResult.OK)
{
this .photoPath = photoFile.FileName;
sendPictureBox.Image = Image.FromFile(photoPath);
}
}
#endregion
#region[定义一个方法将图片存入数据库中]
private void savePhotoToDB(string sendphotoPath)
{
//把图片创成二进制
FileStream myFile = new FileStream(sendphotoPath, FileMode.Open, FileAccess.Read);
byte[] photo = new byte[myFile.Length];
myFile.Read(photo, 0, photo.Length);
myFile.Close();
MessageBox.Show(photo .ToString ());
//将二进制的图片存入数据库中
sqlCon.Open();
string tempSQL = "insert into photo (photo) values (@photo) ";
SqlCommand sqlCom = new SqlCommand(tempSQL, sqlCon);
sqlCom.Parameters.Add("@photo", SqlDbType.Image).Value = photo ;
sqlCom.ExecuteNonQuery();
sqlCon.Close();
}
#endregion
#region[定义一个方法更新图片]
private void updatePhoto(int sendPhotoID,string sendphotoPath)
{
//转换陈二进制
FileStream myFile = new FileStream(sendphotoPath, FileMode.Open, FileAccess.Read);
byte[] photoByte = new byte[myFile.Length];
myFile.Read(photoByte, 0, photoByte.Length);
myFile.Close();
MessageBox.Show(photoByte.ToString());
//更新数据库中的图片
string tempSQL = "update photo set photo=@photo where photoID=" + sendPhotoID;
sqlCon.Open();
SqlCommand sqlCom = new SqlCommand(tempSQL, sqlCon);
sqlCom.Parameters.Add("@photo", SqlDbType.Image).Value = photoByte;
sqlCom.ExecuteNonQuery();
sqlCon.Close();
}
#endregion
private void buttonAdd_Click(object sender, EventArgs e)
{
this.showImageFromFile(this.pictureBox1);
}
private void buttonSave_Click(object sender, EventArgs e)
{
this.savePhotoToDB(photoPath);
}
private void buttonalter_Click(object sender, EventArgs e)
{
this.updatePhoto(Convert.ToInt32(this.textBox1.Text),this .photoPath );
}
private void buttonShow_Click(object sender, EventArgs e)
{
string tempSQL = "select photo from photo where photoID=" + Convert.ToInt32(this.textBox1.Text);
this.sqlCon.Open();
SqlCommand sqlCom = new SqlCommand(tempSQL, sqlCon);
this.pictureBox2.Image = Image.FromStream(new MemoryStream((byte[])sqlCom.ExecuteScalar()));
sqlCon.Close();
}
}
}