您的位置:首页 > 其它

winform 上传图片(留作学习资料)

2009-10-28 02:33 176 查看
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
using System.IO;
namespace ReadImage
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog Dialog = new OpenFileDialog();
Dialog.Filter = "图像文件(*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG";
if (Dialog.ShowDialog() == DialogResult.OK)
{
string FileName = Dialog.FileName;
FileStream fs = new FileStream(FileName, FileMode.Open);
byte[] b=new byte[fs.Length];
BinaryReader br = new BinaryReader(fs);
b = br.ReadBytes(Convert.ToInt32(fs.Length));
string sql = "INSERT INTO [Mag_Rol].[dbo].[ImageTable] VALUES(4,@photo)";
SqlParameter[] param = new SqlParameter[]
{
new SqlParameter("@photo",b)
};
Insert(sql, param);
string select = "select * from [ImageTable] where imageID=@imageID";
SqlParameter[] parameter = new SqlParameter[]
{
new SqlParameter("@imageID",4)
};
SqlDataReader dr = GetData(select, parameter);
dr.Read();
if (dr[1] != DBNull.Value)
{
MemoryStream ms = new MemoryStream((byte[])dr[1]);
Image image = Image.FromStream(ms);
this.pictureBox1.Image = image;
}
else
{
this.pictureBox1.Image = null;
MessageBox.Show("Not Sucessed");
}
conn.Close();
dr.Dispose();
}
}

private static string connectionstring = "server=.;database=Mag_Rol;Integrated Security=sspi";
SqlConnection conn = new SqlConnection(connectionstring);
SqlCommand comm;

public void Insert(string sql,SqlParameter[] param)
{
try
{

conn.Open();
comm = new SqlCommand(sql, conn);
foreach (SqlParameter pa in param)
{
if (pa != null)
{
comm.Parameters.Add(pa);
}
}
comm.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
conn.Close();
comm.Dispose();
}
}

public SqlDataReader GetData(string sql,SqlParameter[] param)
{
try
{
conn.Open();
comm = new SqlCommand(sql, conn);
foreach (SqlParameter pa in param)
{
if (pa != null)
{
comm.Parameters.Add(pa);
}
}
SqlDataReader read = comm.ExecuteReader();
return read;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐