如何将asp.net中的image控件中的图片转换成字节数组

如题所述

鉴于很多同学咨询,如何向数据库中存储并读取图片的方法.在此给出代码,供大家参考.但个人建议,尽量少向数据库中存储如此大二进制数据,会造成数据库过于膨胀,如果采用DataSet读取数据时,当数据量过大还会造成内存严重占用,尤其是在B/S程序设计中,后果会更明显,除非用户强烈要求.一般存储图片时,如无特殊要求,只需要在数据库中存储图片的相对路径即可,将真正的图片存储在指定的文件夹就OK了.当然,两种方式在不同的适用面都有自己的优缺点,下面几篇文章大家可以看看:

以下是存储并显示图片的代码
private void button1_Click(object sender, EventArgs e) //button1的Click事件
//存储图片的代码,需在界面添加按钮Button1,打开文件对话框openFileDialog1,列表框listBox1和图片控件pictureBox1,代码注释部分为SqlServer实现,非注释部分为Access实现,在Access中,数据库名为mydb.mdb,表名为photos,字段为photoid(文本类型,主键),photoimg(OLE对象类型,用于存图片)
{
openFileDialog1.Filter = "*jpg|*.jpg|*bmp|*.bmp|*gif|*.gif";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string fullpath = openFileDialog1.FileName
FileStream fs = new FileStream(fullpath, FileMode.Open, FileAccess.Read);
byte[] imagebytes = new byte[fs.Length];
BinaryReader br = new BinaryReader(fs);
imagebytes = br.ReadBytes(Convert.ToInt32(fs.Length));//把所选图片文件的流中的数据读入字节数组
OleDbConnection conn = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=" + Application.StartupPath + "[url=file://\\mydb.mdb]\\mydb.mdb[/url]");
conn.Open();
OleDbCommand cmd = new OleDbCommand("insert into photos values(@id,@Image)", conn);
cmd.Parameters.Add("@id", OleDbType.VarChar, 50);
cmd.Parameters.Add("@Image", OleDbType.Binary);//图片数据
cmd.Parameters["@id"].Value = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond;
cmd.Parameters["@Image"].Value = imagebytes;//为图片数据的SQL参数赋值
cmd.ExecuteNonQuery();
conn.Close();
//SqlConnection conn = new SqlConnection("server=LENOVO-B2A10C83;database=mydb;uid=sa;pwd=128126");
//conn.Open();
//SqlCommand cmd = new SqlCommand("insert into photos values(@id,@Image)", conn);
//cmd.Parameters.Add("@id", SqlDbType.VarChar, 50);
//cmd.Parameters.Add("@Image", SqlDbType.Image );//与ACCESS数据库唯一不同点
//cmd.Parameters["@id"].Value = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond;
//cmd.Parameters["@Image"].Value = imagebytes;
//cmd.ExecuteNonQuery();
//conn.Close();
MessageBox.Show("图片上传成功");
bindListBox();
}
}
private void bindListBox()//将photoId字段的数据显示在listBox1中,以便查看存入库中的每一个图片
{
OleDbConnection conn = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=" + Application.StartupPath + "[url=file://\\mydb.mdb]\\mydb.mdb[/url]");
OleDbCommand cmd = new OleDbCommand("select photoid from photos");
cmd.Connection = conn;
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
listBox1.DataSource = ds.Tables[0].DefaultView;//设置listBox1的数据源
listBox1.DisplayMember = "photoid";//设置listBox1即将显示数据源中的哪个字段的数据
//SqlConnection conn = new SqlConnection("server=LENOVO-B2A10C83;database=mydb;uid=sa;pwd=128126");
//SqlCommand cmd = new SqlCommand("select photoid from photos");
//cmd.Connection = conn;
//SqlDataAdapter da = new SqlDataAdapter();
//da.SelectCommand = cmd;
//DataSet ds = new DataSet();
//da.Fill(ds);
//listBox1.DataSource = ds.Tables[0].DefaultView;
//listBox1.DisplayMember = "photoid";
}
private void Form1_Load(object sender, EventArgs e) //Form1的Load事件
{
bindListBox();//程序加载时,先将数据库中现有的数据显示在listBox1中
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)//listBox1的SelectedIndexChanged事件,当在listBox1中选择不同的photoId时,pictureBox1中显示该photoId对应的图片
{
OleDbConnection conn = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=" + Application.StartupPath + "[url=file://\\mydb.mdb]\\mydb.mdb[/url]");
OleDbCommand cmd = new OleDbCommand("select photoimg from photos where photoid='" + ((DataRowView)(listBox1.SelectedValue))[0] + "'");//将listBox1中选中的photoId所对应的图片数据从数据库中取出来
cmd.Connection = conn;
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
dr.Read();
byte[] b = (byte[])dr[0];//将图片数据转换成字节数组
MemoryStream stmBLOBData = new MemoryStream(b);//将该字节数组转换成内存流
pictureBox1.Image = Image.FromStream(stmBLOBData);//将该内存流转换成Image对象,并显示在pictureBox1中
//SqlConnection conn = new SqlConnection("server=LENOVO-B2A10C83;database=mydb;uid=sa;pwd=128126");
//SqlCommand cmd = new SqlCommand("select photoimg from photos where photoid='" + ((DataRowView)(listBox1.SelectedValue))[0] + "'");
//cmd.Connection = conn;
//conn.Open();
//SqlDataReader dr = cmd.ExecuteReader();
//dr.Read();
//byte[] b = (byte[])dr[0];
//MemoryStream stmBLOBData = new MemoryStream(b);
//pictureBox1.Image = Image.FromStream(stmBLOBData);
}
另外,站长团上有产品团购,便宜有保证
温馨提示:内容为网友见解,仅供参考
第1个回答  2011-06-30
鉴于很多同学咨询,如何向数据库中存储并读取图片的方法.在此给出代码,供大家参考.但个人建议,尽量少向数据库中存储如此大二进制数据,会造成数据库过于膨胀,如果采用DataSet读取数据时,当数据量过大还会造成内存严重占用,尤其是在B/S程序设计中,后果会更明显,除非用户强烈要求.一般存储图片时,如无特殊要求,只需要在数据库中存储图片的相对路径即可,将真正的图片存储在指定的文件夹就OK了.当然,两种方式在不同的适用面都有自己的优缺点,下面几篇文章大家可以看看:

以下是存储并显示图片的代码
private void button1_Click(object sender, EventArgs e) //button1的Click事件
//存储图片的代码,需在界面添加按钮Button1,打开文件对话框openFileDialog1,列表框listBox1和图片控件pictureBox1,代码注释部分为SqlServer实现,非注释部分为Access实现,在Access中,数据库名为mydb.mdb,表名为photos,字段为photoid(文本类型,主键),photoimg(OLE对象类型,用于存图片)
{
openFileDialog1.Filter = "*jpg|*.jpg|*bmp|*.bmp|*gif|*.gif";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string fullpath = openFileDialog1.FileName
FileStream fs = new FileStream(fullpath, FileMode.Open, FileAccess.Read);
byte[] imagebytes = new byte[fs.Length];
BinaryReader br = new BinaryReader(fs);
imagebytes = br.ReadBytes(Convert.ToInt32(fs.Length));//把所选图片文件的流中的数据读入字节数组
OleDbConnection conn = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=" + Application.StartupPath + "[url=file://\\mydb.mdb]\\mydb.mdb[/url]");
conn.Open();
OleDbCommand cmd = new OleDbCommand("insert into photos values(@id,@Image)", conn);
cmd.Parameters.Add("@id", OleDbType.VarChar, 50);
cmd.Parameters.Add("@Image", OleDbType.Binary);//图片数据
cmd.Parameters["@id"].Value = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond;
cmd.Parameters["@Image"].Value = imagebytes;//为图片数据的SQL参数赋值
cmd.ExecuteNonQuery();
conn.Close();
//SqlConnection conn = new SqlConnection("server=LENOVO-B2A10C83;database=mydb;uid=sa;pwd=128126");
//conn.Open();
//SqlCommand cmd = new SqlCommand("insert into photos values(@id,@Image)", conn);
//cmd.Parameters.Add("@id", SqlDbType.VarChar, 50);
//cmd.Parameters.Add("@Image", SqlDbType.Image );//与ACCESS数据库唯一不同点
//cmd.Parameters["@id"].Value = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond;
//cmd.Parameters["@Image"].Value = imagebytes;
//cmd.ExecuteNonQuery();
//conn.Close();
MessageBox.Show("图片上传成功");
bindListBox();
}
}
private void bindListBox()//将photoId字段的数据显示在listBox1中,以便查看存入库中的每一个图片
{
OleDbConnection conn = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=" + Application.StartupPath + "[url=file://\\mydb.mdb]\\mydb.mdb[/url]");
OleDbCommand cmd = new OleDbCommand("select photoid from photos");
cmd.Connection = conn;
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
listBox1.DataSource = ds.Tables[0].DefaultView;//设置listBox1的数据源
listBox1.DisplayMember = "photoid";//设置listBox1即将显示数据源中的哪个字段的数据
//SqlConnection conn = new SqlConnection("server=LENOVO-B2A10C83;database=mydb;uid=sa;pwd=128126");
//SqlCommand cmd = new SqlCommand("select photoid from photos");
//cmd.Connection = conn;
//SqlDataAdapter da = new SqlDataAdapter();
//da.SelectCommand = cmd;
//DataSet ds = new DataSet();
//da.Fill(ds);
//listBox1.DataSource = ds.Tables[0].DefaultView;
//listBox1.DisplayMember = "photoid";
}
private void Form1_Load(object sender, EventArgs e) //Form1的Load事件
{
bindListBox();//程序加载时,先将数据库中现有的数据显示在listBox1中
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)//listBox1的SelectedIndexChanged事件,当在listBox1中选择不同的photoId时,pictureBox1中显示该photoId对应的图片
{
OleDbConnection conn = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=" + Application.StartupPath + "[url=file://\\mydb.mdb]\\mydb.mdb[/url]");
OleDbCommand cmd = new OleDbCommand("select photoimg from photos where photoid='" + ((DataRowView)(listBox1.SelectedValue))[0] + "'");//将listBox1中选中的photoId所对应的图片数据从数据库中取出来
cmd.Connection = conn;
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
dr.Read();
byte[] b = (byte[])dr[0];//将图片数据转换成字节数组
MemoryStream stmBLOBData = new MemoryStream(b);//将该字节数组转换成内存流
pictureBox1.Image = Image.FromStream(stmBLOBData);//将该内存流转换成Image对象,并显示在pictureBox1中
//SqlConnection conn = new SqlConnection("server=LENOVO-B2A10C83;database=mydb;uid=sa;pwd=128126");
//SqlCommand cmd = new SqlCommand("select photoimg from photos where photoid='" + ((DataRowView)(listBox1.SelectedValue))[0] + "'");
//cmd.Connection = conn;
//conn.Open();
//SqlDataReader dr = cmd.ExecuteReader();
//dr.Read();
//byte[] b = (byte[])dr[0];
//MemoryStream stmBLOBData = new MemoryStream(b);
//pictureBox1.Image = Image.FromStream(stmBLOBData);
}

asp.net怎么从数据库某个字段中截取图片并保存到数组中?
例如 11.jpg 然后自己手写<img src=“phon\\<%Eval("img")%>”>呢。。

怎么将图片转换成二进制,存入数据库,然后怎么读出来并显示
FileStream fs = new FileStream(fileName, FileMode.Open);int streamLength = (int)fs.Length;byte[] image = new byte[streamLength];fs.Read(image, 0, streamLength);fs.Close();return image;} \/\/另外,在ASP.NET中通过FileUpload控件得到的图像文件可以通过以下方法 public byte[] SetImage...

asp.net mvc怎么做到把数据库里面图片的存储地址读出来,然后显示在中...
后台:public ActionResult action() { string path = "读取数据库里面的图片路径"; byte[] img = System.IO.File.ReadAllBytes(path);\/\/将图片读入字节数组 return new FileContentResult(img, "image\/jpeg");\/\/返回图片 } ...

如何在ASP.Net 中把图片存入数据库
我们需要一个字节型数组来存储image 内容 读取整个图片可以使用Stream对象的Read方法来实现 Read(in byte[] buffer int offset int count)方法有三个参数 【关于Read方法的详细内容可以参看 Net FrameWorkSDK】 他们是 buffer 字节数组 此方法返回时 该缓冲区包含指定的字符数组 该数组的 offset 和 (o...

如何用ASP.NET想数据库中存取图片
byte[] b = (byte[])dr[0];\/\/将图片数据转换成字节数组 MemoryStream stmBLOBData = new MemoryStream(b);\/\/将该字节数组转换成内存流 pictureBox1.Image = Image.FromStream(stmBLOBData);\/\/将该内存流转换成Image对象,并显示在pictureBox1中 \/\/SqlConnection conn = new SqlConnection("...

asp.net 图片转成base64位流, 怎么转后在转成图片图片显示不全
asp.net图片转base64方法如下,在确保数据完整的情况下是不会有显示不全的情况出现。< Function ImagesToBase64(FileName)Dim xml Dim root Dim fs Dim FilePath Dim objStream Dim objXMLDoc Dim Base64 ''定义变量完结 '创建对像 FilePath=Server.MapPath(FileName)getFileExt = Mid(FilePath, ...

asp.net将图片存入数据库中,图片长度的问题
那样是吃力不讨好的事,如果你一定要这样做,那么请把你的strsql="insert tb_Image (ImageFile)values('"+fileDate+"')";改用存储过程,用参数进行传递,你以上这句话本身有毛病:('"+fileDate+"')">>fileDate:在这里已是字符数据,但它本身却是字节数组....

img 显示数据库里的图片 怎么是随机显示啊 asp.net
sql语句 new_id关键字 随机从表里取数据

asp.net中如何把字节流格式化为图片形式
image.Save(ms, ImageFormat.Jpeg); \/\/把图片保存在内存流里面,格式为Jpeg格式 ms.Flush(); \/\/关闭内存流 byte[] b=ms.GetBuffer(); \/\/直接获得2进制byte数组 \/\/b就是这个图片的字节流

asp.net中如何将二进制图片存入有id(自增长、主键)、studentid(从登陆页...
sr.Read(FileData, 0, FileLen);\/\/将图片数据放到FileData数组对象实例中,其中0代表数组指针的起始位置,FileLen表示要读取流的长度(指针的结素位置)\/\/SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["imges"]);con.Open();\/\/写入数据库 SqlCommand com = new SqlCommand("...

相似回答