在开发的过程中,难免遇到图片保存问题,解决的方法有很多,这里我把图片以二进制的形式保存到数据库中,也许这个形式并不是最高效的方式,但也不失为一种好的方法吧.呵呵,下面简单的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;
}