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);
}
}
}
}
本文介绍了一个使用C#实现的图片上传功能,并将其保存为二进制格式到数据库中,同时展示了如何从数据库读取这些图片并显示在应用程序界面上。
1155

被折叠的 条评论
为什么被折叠?



