当前位置: 移动技术网 > IT编程>开发语言>.net > Asp.net把图片存入数据库和读取图片的方法

Asp.net把图片存入数据库和读取图片的方法

2017年12月12日  | 移动技术网IT编程  | 我要评论
网上关于asp.net上传图片到数据库的资料非常多,常用的如下:存储图片类型数据有以下几种方式:1.将图片转换为二进制数组(byte[])复制代码 代码如下:byte[]
网上关于asp.net上传图片到数据库的资料非常多,常用的如下:
存储图片类型数据有以下几种方式:
1.将图片转换为二进制数组(byte[])
复制代码 代码如下:

byte[] filedata = this.fileupload1.filebytes;

2. 根据路径将文件转换为2进制数组
复制代码 代码如下:

代码
public byte[] returnbyte(string strpath)
{
 // 以二进制方式读文件
    filestream fsmyfile = new filestream(strpath, filemode.openorcreate, fileaccess.readwrite);
// 创建一个二进制数据流读入器,和打开的文件关联
    binaryreader brmyfile = new binaryreader(fsmyfile);
// 把文件指针重新定位到文件的开始
    brmyfile.basestream.seek(0, seekorigin.begin);
   byte[] bytes = brmyfile.readbytes(convert.toint32(fsmyfile.length.tostring()));
// 关闭以上new的各个对象
    brmyfile.close();
   return bytes;
}

3img 类型得到二进制数组
复制代码 代码如下:

public static byte[] getbyte(image img)
{
    memorystream stream = new memorystream();
    img.save(stream, imageformat.jpeg);
    byte[] mydata = new byte[stream.length];
    mydata = stream.toarray();
    stream.close();
    return mydata;
 }

读取image类型的数据并显示在网页上的方式如下:
1。直接返回image 类型
复制代码 代码如下:

private system.drawing.image getimagedatafromoracle()
{
string sql = "select imgdata from t_img where imgid=100";
string strconn = system.configuration.configurationmanager.connectionstrings["connectionstringfororacle"].tostring();
oracleconnection oraconn = new oracleconnection(strconn);
oraclecommand oracomm = new oraclecommand(sql, oraconn);
oraconn.open();
byte[] filedata = (byte[])oracomm.executescalar();
oraconn.close();
system.io.memorystream ms = new system.io.memorystream(filedata);
system.drawing.image img = system.drawing.image.fromstream(ms);
return img;
}

2.利用页面输入来显示图片
页面imageshow.aspx (page_load方法)
复制代码 代码如下:

 protected void page_load(object sender, eventargs e)
{
  byte[] b_logoimg = (byte[])dt_channelimg.rows[0]["logoimage"]; //得到byte[] 数组,这里只是举个例子
   if (b_logoimg.length > 0)
   {
    system.drawing.image logoimg;
    memorystream ms = new memorystream(b_logoimg);
    response.clear();
    response.contenttype = "image/gif";
    response.outputstream.write(b_logoimg, 0, b_logoimg.length);
    response.end();
  }
}

图片路径写成为:<img src = "imageshow.aspx" />

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

相关文章:

验证码:
移动技术网