日期:2014-05-19  浏览次数:20804 次

读出数据库的图片并绑定到image控件上?(C#)
数据库里有一个用二进制存放image的字段,需要在界面上显示出来或者绑定到image控件上?

------解决方案--------------------
http://www.163vc.com/Article/biancheng/net/200611/40208.html
------解决方案--------------------
SqlDataReader dr;
if (IMGID != string.Empty)
{

this.Response.ContentType = "image/* ";
dr = (SqlDataReader)oDALObject.DatabaseAccess.ExecuteReader(string.Format( "select ImageData from Photo_Lib_tmp where IMG_ID= '{0} ' ", IMGID));

while (dr.Read())
{
if (dr[ "ImageData "] != null && dr[ "ImageData "].ToString()!=string.Empty)
{
this.Response.BinaryWrite((byte[])dr[ "ImageData "]);
}
}
dr.Close();
}

备注:oDALObject为 我自己的数据操作类,你改为你的方式就行了,反正执行个sql.
ImageData位存储图片的字段.

将此代码写在个aspx页里(该页用来显示图片).


具体要显示图片的页面:

image方式:
<img src= '刚才aspx页面地址 ' />
------解决方案--------------------
http://blog.csdn.net/zhangshg2008/archive/2007/02/02/1501140.aspx
会对你有帮助
------解决方案--------------------
-------Web界面Img-----------
<img src= "Handler.ashx?PhotoID= <%# Eval( "PhotoID ") %> &Size=S " class= "photo_198 " style= "border:4px solid white " alt= '缩略图,照片编号 <%# Eval( "PhotoID ") %> ' />

--------Handler.ashx---------
<%@ WebHandler Language= "C# " Class= "Handler " %>

using System;
using System.IO;
using System.Web;

public class Handler : IHttpHandler {

public bool IsReusable {
get {
return true;
}
}

public void ProcessRequest (HttpContext context) {
// 设置响应设置
context.Response.ContentType = "image/jpeg ";
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.BufferOutput = false;
// 设置 Size 参数
PhotoSize size;
switch (context.Request.QueryString[ "Size "]) {
case "S ":
size = PhotoSize.Small;
break;
case "M ":
size = PhotoSize.Medium;
break;
case "L ":
size = PhotoSize.Large;
break;
default:
size = PhotoSize.Original;
break;
}
// 设置 PhotoID 参数
Int32 id = -1;
Stream stream = null;
if (context.Request.QueryString[ "PhotoID "] != null && context.Request.QueryString[ "PhotoID "] != " ") {
id = Convert.ToInt32(context.Request.QueryString[ "PhotoID "]);
stream = PhotoManager.GetPhoto(id, size);
} else {
id = Convert.ToInt32(context.Request.QueryString[ "AlbumID "]);
stream = PhotoManager.GetFirstPhoto(id, size);
}
// 从数据库获取照片,如果未返回照片,将获取默认的“placeholder”照片
if (stream == null) stream = PhotoManager.GetPhoto(size);
// 将图像流写入响应流中
const int buffersize = 1024 * 16;
byte[] buffer = new byte[buffersize];
int count = stream.Read(buffer, 0, buffersize);
while (count > 0) {
context.Response.OutputStream.Write(buffer, 0, count);
count = stream.Read(buffer, 0, buffersize);
}
}

}