两张方式获取数据库的二进制图片
1、用aspx 的Page_Load事件获取;(适用于单张图片显示)
2、用ashx类 一般处理事件 获取;(适用于一组图片显示)
显示图片的网页:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr><td>aspx方式显示图片</td></tr>
<tr>
<td>
<asp:Image ID="image1" Width="100" Height="100" runat="server" ImageUrl="Default5.aspx" />
</td>
</tr>
<tr><td>ashx方式显示图片</td></tr>
<tr>
<td>
<asp:Image ID="image2" runat="server" Width="100" Height="100" ImageUrl="Getimg.ashx" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
1、获取图片的网页
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Text;
public partial class Default5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string conSql = "";
SqlConnection conn = new SqlConnection(conSql);
SqlCommand com = new SqlCommand();
com.Connection = conn;
StringBuilder comText = new StringBuilder();
comText.Append("select ImageCol from Image_Table");
com.CommandText = comText.ToString();
conn.Open();
byte[] file = (byte[])com.ExecuteScalar();
System.IO.MemoryStream stream = null;
try
{
Response.ContentType = "image/jpeg";
stream = new System.IO.MemoryStream(file);
int buffersize = 1024 * 16;
byte[] buffer = new byte[buffersize];
int conentsize = stream.Read(buffer, 0, buffersize);
while (conentsize > 0)
{
//将缓冲区的输入输出到页面
Response.OutputStream.Write(buffer, 0, conentsize);
conentsize = stream.Read(buffer, 0, buffersize);
}
}
catch
{
}
finally
{
if (stream != null)
stream.Close();
}
}
}
<%@ WebHandler Language="C#" Class="Getimg" %>
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public class Getimg : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
string conSql = "";
SqlConnection conn = new SqlConnection(conSql);
SqlCommand com = new SqlCommand();
com.Connection = conn;
System.Text.StringBuilder comText = new System.Text.StringBuilder();
comText.Append("select ImageCol from Image_Table");
com.CommandText = comText.ToString();
conn.Open();
SqlDataReader dr = com.ExecuteReader();
System.IO.MemoryStream stream = null;
if (dr.Read())
{
byte[] file = (byte[])dr["ImageCol"];
context.Response.ContentType = "image/jpeg";
stream = new System.IO.MemoryStream(file);
int buffersize = 1024 * 16;
byte[] buffer = new byte[buffersize];
int conentsize = stream.Read(buffer, 0, buffersize);
while (conentsize > 0)
{
context.Response.OutputStream.Write(buffer, 0, conentsize);
conentsize = stream.Read(buffer, 0, buffersize);
}
}
dr.Close();
}
public bool IsReusable {
get {
return false;
}
}
}