网上关于ASPNET上传图片到数据库的资料非常多常用的如下:
存储图片类型数据有以下几种方式
将图片转换为二进制数组(byte[])
复制代码 代码如下:
byte[] fileData = this
FileUpload
FileBytes;
根据路径将文件转换为进制数组
复制代码 代码如下:
代码
public byte[] returnbyte(string strpath)
{
// 以二进制方式读文件
FileStream fsMyfile = new FileStream(strpath
FileMode
OpenOrCreate
FileAccess
ReadWrite);
// 创建一个二进制数据流读入器
和打开的文件关联
BinaryReader brMyfile = new BinaryReader(fsMyfile);
// 把文件指针重新定位到文件的开始
brMyfile
BaseStream
Seek(
SeekOrigin
Begin);
byte[] bytes = brMyfile
ReadBytes(Convert
ToInt
(fsMyfile
Length
ToString()));
// 关闭以上new的各个对象
brMyfile
Close();
return bytes;
}
img 类型得到二进制数组
复制代码 代码如下:
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类型的数据并显示在网页上的方式如下
直接返回image 类型
复制代码 代码如下:
private System
Drawing
Image getImageDataFromOracle()
{
string sql = "select IMGDATA from t_img where imgID=
";
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;
}
利用页面输入来显示图片
页面ImageShowaspx (Page_Load方法)
复制代码 代码如下:
protected void Page_Load(object sender
EventArgs e)
{
byte[] b_logoImg = (byte[])dt_channelImg
Rows[
]["LogoImage"]; //得到byte[] 数组
这里只是举个例子
if (b_logoImg
Length >
)
{
System
Drawing
Image logoImg;
MemoryStream ms = new MemoryStream(b_logoImg);
Response
Clear();
Response
ContentType = "image/gif";
Response
OutputStream
Write(b_logoImg
b_logoImg
Length);
Response
End();
}
}
图片路径写成为<img src = "ImageShowaspx" />