您的位置:首页 > 数据库

图片存到数据库,并在页面读取出来

2013-01-06 20:21 756 查看
(一)将图片存储到数据库中(注:本文讨论的数据库是sql server)
在sql server专门有存储图片的数据类型image,我们可以很方便的使用,我比较习惯根据代码来讲解……

[c-sharp] view plaincopyprint?#region 执行sql语句存储图片
/// <summary>
/// 执行sql语句存储图片
/// </summary>
/// <param name="ProcName">sql语句</param>
/// <param name="prams">参数</param>
public static void StoreImage(string ProcName, SqlParameter[] prams)
{
try
{
SqlCommand cmd = CreateCommand(ProcName, prams, CommandType.Text);
cmd.ExecuteNonQuery();
}
finally
{
CloseConn();
}
}
#endregion

#region 将图片转换为byte数组
/// <summary>
/// 将图片转换为byte数组
/// </summary>
/// <param name="strFullPath">图片的完整路径</param>
/// <returns>byte[]</returns>
public static byte[] ImageToByte(string strFullPath)
{
byte[] imagebyte = null;
FileStream fs = new FileStream(strFullPath, FileMode.Open);
BinaryReader br = new BinaryReader(fs);
imagebyte = br.ReadBytes((int)fs.Length);
return (imagebyte);
}
#endregion
#region 执行sql语句存储图片
/// <summary>
/// 执行sql语句存储图片
/// </summary>
/// <param name="ProcName">sql语句</param>
/// <param name="prams">参数</param>
public static void StoreImage(string ProcName, SqlParameter[] prams)
{
try
{
SqlCommand cmd = CreateCommand(ProcName, prams, CommandType.Text);
cmd.ExecuteNonQuery();
}
finally
{
CloseConn();
}
}
#endregion

#region 将图片转换为byte数组
/// <summary>
/// 将图片转换为byte数组
/// </summary>
/// <param name="strFullPath">图片的完整路径</param>
/// <returns>byte[]</returns>
public static byte[] ImageToByte(string strFullPath)
{
byte[] imagebyte = null;
FileStream fs = new FileStream(strFullPath, FileMode.Open);
BinaryReader br = new BinaryReader(fs);
imagebyte = br.ReadBytes((int)fs.Length);
return (imagebyte);
}
#endregion

函数StoreImage中的ProcName是存储图片的sql语句,prams是一个数组,用来存储插入语句需要使用的参数,我这样做主要是因为把我函数写在公共类里面方便重复使用。insert into tb_class(classID,className,classImage) values(@classID,@className,@image),插入图片和插入其他数据没有什么不一样的,我们需要做的是就是在插入之前调用ImageToByte()函数将图片转换成byte数组,然后将byte[]存入数据库.

(二)将图片显示在网页上面

显示也可以说是成数据库中读取byte[]然后转换成图片,是存储的逆向过程。我们这里考虑2中情况下的图片读取:1.图片很大时,如4M; 2.需要将图片和文字混合显示。现在依次讲解

<1>step by step方式

[c-sharp] view plaincopyprint?#region 从数据库中读取图片,显示在当前页面
/// <summary>
/// 从数据库中读取图片,显示在当前页面(显示方式:step by step)
/// </summary>
/// <param name="ProcName">sql语句,查询字段为数据库中图片字段</param>
/// <param name="prams">参数</param>
/// <param name="Size">一次显示的字节数</param>
/// <param name="p">需要显示图片的页面,只能为this.page</param>
public static void GetImage(string ProcName, SqlParameter[] prams,int Size,Page p)
{
try
{
SqlCommand cmd = CreateCommand(ProcName, prams, CommandType.Text);
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
byte[] bytes = null;
if (dr.Read())
{
int bufferSize = Size; //size of buffer.
bytes = new byte[bufferSize]; //the buffer of data.
long bytesRead; //the number of bytes read.
long readForm = 0; //the starting index.

//read the filed 100 bytes at a time.
do
{
bytesRead = dr.GetBytes(0, readForm, bytes, 0, bufferSize);
p.Response.BinaryWrite(bytes);
readForm += bufferSize;
} while (bytesRead == bufferSize);
}
dr.Close();
}
finally
{
CloseConn();
}
}
#endregion
#region 从数据库中读取图片,显示在当前页面
/// <summary>
/// 从数据库中读取图片,显示在当前页面(显示方式:step by step)
/// </summary>
/// <param name="ProcName">sql语句,查询字段为数据库中图片字段</param>
/// <param name="prams">参数</param>
/// <param name="Size">一次显示的字节数</param>
/// <param name="p">需要显示图片的页面,只能为this.page</param>
public static void GetImage(string ProcName, SqlParameter[] prams,int Size,Page p)
{
try
{
SqlCommand cmd = CreateCommand(ProcName, prams, CommandType.Text);
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
byte[] bytes = null;
if (dr.Read())
{
int bufferSize = Size; //size of buffer.
bytes = new byte[bufferSize]; //the buffer of data.
long bytesRead; //the number of bytes read.
long readForm = 0; //the starting index.

//read the filed 100 bytes at a time.
do
{
bytesRead = dr.GetBytes(0, readForm, bytes, 0, bufferSize);
p.Response.BinaryWrite(bytes);
readForm += bufferSize;
} while (bytesRead == bufferSize);
}
dr.Close();
}
finally
{
CloseConn();
}
}
#endregion

这个函数主要将图片分布显示出来,每次读取Size大小,直到没有数据可以读取(显示完毕)为止。其中page p指的是要显示图片的页面,呵呵,这也是这个方法的缺点所在:p必须为调用这个函数的页面,也就是this;同时这个页面只能显示这一个图片,呵呵,是不是很郁闷,下面介绍第二种方法。

<2>图文混排

首先在解决方案下新建一个.ashx文件(imageFromDb.ashx),在文件内删除部分代码,只保留以下代码[c-sharp] view plaincopyprint?<%@ WebHandler Language="C#" Class="imageFromDb" %>
<%@ WebHandler Language="C#" Class="imageFromDb" %>

新建一个类,名为imageFromDb.cs,写如一下代码

[c-sharp] view plaincopyprint?using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;

public class imageFromDb : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
string id = context.Request.QueryString["id"];
string type = context.Request.QueryString["type"];
string sql = null;
if (id == null) throw new ApplicationException("must specify ID");
if (type == null) throw new ApplicationException("must specify type");
SqlConnection conn = DBForSQL.CreateConn();
if (type == "class")
{
sql = "select classImage from tb_class where classID=@ID";
}
else if(type=="goods")
{
sql = "select goodsImage from tb_goods where goodsID=@ID";
}
if (sql != null)
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@ID", id);

try
{
conn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
if (dr.Read())
{
int bufferSize = 100;
byte[] bytes = new byte[bufferSize];
long bytesRead;
long readFrom = 0;
do
{
bytesRead = dr.GetBytes(0, readFrom, bytes, 0, bufferSize);
context.Response.BinaryWrite(bytes);
readFrom += bufferSize;
} while (bytesRead == bufferSize);
}
dr.Close();
}
finally
{
conn.Close();
}
}

}

public bool IsReusable
{
get
{
return true;
}
}

}
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;

public class imageFromDb : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
string id = context.Request.QueryString["id"];
string type = context.Request.QueryString["type"];
string sql = null;
if (id == null) throw new ApplicationException("must specify ID");
if (type == null) throw new ApplicationException("must specify type");
SqlConnection conn = DBForSQL.CreateConn();
if (type == "class")
{
sql = "select classImage from tb_class where classID=@ID";
}
else if(type=="goods")
{
sql = "select goodsImage from tb_goods where goodsID=@ID";
}
if (sql != null)
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@ID", id);

try
{
conn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
if (dr.Read())
{
int bufferSize = 100;
byte[] bytes = new byte[bufferSize];
long bytesRead;
long readFrom = 0;
do
{
bytesRead = dr.GetBytes(0, readFrom, bytes, 0, bufferSize);
context.Response.BinaryWrite(bytes);
readFrom += bufferSize;
} while (bytesRead == bufferSize);
}
dr.Close();
}
finally
{
conn.Close();
}
}

}

public bool IsReusable
{
get
{
return true;
}
}

}

这个类中的部分细节(如查询语句)读者可以自己更改

最后要做的就是在html控件img中显示图片了,方法如下

<img alt="" src="imageFromDB.ashx?id=<%#goodsID %>&type=goods"  style="height: 196px; width: 209px" />

ok完成了,图片可以显示了,并且不会影响网页中其他内容,不过建议你使用<img>控件,这样会减少很多麻烦……
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐