当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET实现图片以二进制的形式存入数据库

ASP.NET实现图片以二进制的形式存入数据库

2017年12月12日  | 移动技术网IT编程  | 我要评论
本文以实例形式讲述了asp.net实现图片以二进制的形式存入数据库的方法。过去我们都是直接在数据库中存入图片文件名的,还没有试过存储整张图片到数据库中,经过一番资料查询与测

本文以实例形式讲述了asp.net实现图片以二进制的形式存入数据库的方法。过去我们都是直接在数据库中存入图片文件名的,还没有试过存储整张图片到数据库中,经过一番资料查询与测试,整理出了如下的功能代码:

1.建立保存图片的表的sql语句:

use [niunantest] 
go 
/****** 对象: table [dbo].[picdata]  脚本日期: 03/30/2010 14:51:58 ******/ 
set ansi_nulls on 
go 
set quoted_identifier on 
go 
create table [dbo].[picdata]( 
  [id] [int] identity(1,1) not null, 
  [content] [image] null, 
  [createdate] [datetime] not null constraint [df_picdata_createdate] default (getdate()), 
 constraint [pk_picdata] primary key clustered  
( 
  [id] asc 
)with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [primary] 
) on [primary] textimage_on [primary] 

2.下面是保存图片到数据库中的代码片段:

int len = fu.postedfile.contentlength; // 图片大小 
byte[] pic = new byte[len]; // 创建一个字节数组,大小为图片的大小,数据库中就存储这个东西 
fu.postedfile.inputstream.read(pic, 0, len); // 把上传控件中的文件用二进制读取存到pic字节数组中 
//  插入图片到数据库中    
sqlconnection connection = new 
sqlconnection(@"server=.\sqlexpress;database=niunantest;uid=sa;pwd=123456"); 
try 
{ 
  connection.open(); 
  sqlcommand cmd = new sqlcommand("insert  into  picdata  " 
  + "([content])  values  (@pic)", connection); 
  cmd.parameters.add("@pic", pic); 
  cmd.executenonquery(); 
  label1.text = "图片插入数据库成功!"; 
 
  image1.imageurl = "getpic.ashx?t=" + datetime.now.ticks; // 显示刚刚插入数据库的图片 
} 
finally 
{ 
  connection.close(); 
}  
 

3.下面是从数据库中取出图片的代码片段:

memorystream stream = new memorystream(); 
sqlconnection connection = new 
sqlconnection(@"server=.\sqlexpress;database=niunantest;uid=sa;pwd=123456"); 
try 
{ 
  connection.open(); 
  sqlcommand command = new 
  sqlcommand("select top 1 [content]  from  picdata order by id desc", connection); 
  byte[] image = (byte[])command.executescalar(); 
  stream.write(image, 0, image.length); 
  bitmap bitmap = new bitmap(stream); 
  context.response.contenttype = "image/jpeg"; 
  bitmap.save(context.response.outputstream, system.drawing.imaging.imageformat.jpeg); 
} 
finally 
{ 
  connection.close(); 
  stream.close(); 
}

程序的原理其实也就是通过流把图片搞成字节数组再存到数据库中,然后再从数据库中读取字节数组出来,再通过字节数组创建流,再通过流把图像输出出来,发现你存到数据库中的是gif图像的话再取出来是可以把他转为jpg的图像的,因为在取出图像的时候我们设置他的contenttype是image/jpeg了。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网