ImageHandler question
am 19.12.2007 23:48:31 von gsaunsI have a Generic Handler file that I use to display images stored in a
database (SQL 2005, stored as varbinary fields).
I pulled most of the code from the web, and it works great. I have
recently added functionality to change the photo via selections from a
radiobuttonlist. That also works great. What I would like to do is to
display an alternate image instead of the alternate text. I have the
image in a .jpg file. The question is, how can I get the MemoryStream
from this .jpg file? Is it possible to read that from a saved jpg on
the file system? I will always know where that alternate image resides
on the server. Here is the handler code:
<%@ WebHandler Language="C#" Class="ImageHandler" %>
using System;
using System.IO;
using System.Web;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
public class ImageHandler : IHttpHandler {
public bool IsReusable {
get {
return true;
}
}
public static Stream GetPhoto2(int photoid, string strSelection)
{
using (SqlConnection connection = new
SqlConnection(ConfigurationManager.ConnectionStrings["Conn_S tring"].ConnectionString))
{
using (SqlCommand command = new SqlCommand(strSelection,
connection))
{
command.Parameters.Add(new SqlParameter("@id", photoid));
connection.Open();
object result = command.ExecuteScalar();
try
{
return new MemoryStream((byte[])result);
}
catch
{
// MemoryStream of alternate image would be read in
here.
return null;
}
}
}
}
public void ProcessRequest (HttpContext context)
{
//Set up the response settings
context.Response.ContentType = "image/jpeg";
context.Response.Cache.SetCacheability(HttpCacheability.Publ ic);
context.Response.BufferOutput = false;
// Setup the PhotoID Parameter
string sel;
Int32 id = -1;
Stream stream = null;
id = Convert.ToInt32(context.Request.QueryString["cplyr_id"]);
switch (context.Request.QueryString["img"].ToString())
{
case "front":
sel = "SELECT FRONT_PHOTO FROM TABLE WHERE ID=@id";
break;
case "back":
sel = "SELECT BACK_PHOTO FROM TABLE WHERE ID=@id";
break;
case "head":
sel = "SELECT HEAD_PHOTO FROM TABLE WHERE ID=@id";
break;
default:
sel = "SELECT FRONT_PHOTO FROM TABLE WHERE ID=@id";
break;
}
stream = GetPhoto2(id,sel);
const int buffersize = 1024 * 16;
byte[] buffer2 = new byte[buffersize];
int count = stream.Read(buffer2, 0, buffersize);
while (count > 0) {
context.Response.OutputStream.Write(buffer2, 0, count);
count = stream.Read(buffer2, 0, buffersize);
}
}
}