Return Image from Generic Handler that stored in Sql Server Database Varbinary Database Asp.Net C#
<%@ WebHandler Language="C#" Class="GalleryImg" %>
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
public class GalleryImg : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
int id;
if (context.Request.QueryString["id"] != null || context.Request.QueryString["id"] != "")
{
id = Convert.ToInt32(context.Request.QueryString["id"]);
context.Response.ContentType = "image/jpeg";
Stream strm = DisplayImage(id);
byte[] buffer = new byte[2048];
int byteSeq = strm.Read(buffer, 0, 2048);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 2048);
}
}
}
public Stream DisplayImage(int id)
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString.ToString());
string sql = "SELECT Image FROM Tbl_Gallery WHERE id='" + id + "'";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
connection.Open();
object theImg = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])theImg);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
public class GalleryImg : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
int id;
if (context.Request.QueryString["id"] != null || context.Request.QueryString["id"] != "")
{
id = Convert.ToInt32(context.Request.QueryString["id"]);
context.Response.ContentType = "image/jpeg";
Stream strm = DisplayImage(id);
byte[] buffer = new byte[2048];
int byteSeq = strm.Read(buffer, 0, 2048);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 2048);
}
}
}
public Stream DisplayImage(int id)
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString.ToString());
string sql = "SELECT Image FROM Tbl_Gallery WHERE id='" + id + "'";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
connection.Open();
object theImg = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])theImg);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
Comments
Post a Comment