Tuesday, June 30, 2009

Access image through url and render as jpeg in asp.net

class ImageProcessingModule : IHttpModule
{
public void Init(System.Web.HttpApplication context)
{
context.BeginRequest += new EventHandler(OnBeginRequest);
}
private void OnBeginRequest(object sender, EventArgs e)
{
HttpApplication app;
string requestUrl;

app = sender as HttpApplication;
requestUrl = app.Request.Url.ToString();
//requestUrl=requestUrl.Replace("https://", "http://");


//if (!requestUrl.ToLower().Contains("products")) { return; }
string[] strUrl = requestUrl.Split('/');
string ProductCode = string.Empty;
string Size = string.Empty;

for (int i = 0; i < strUrl.Length; i++)
{
if (strUrl[i].ToLower() == "images" && strUrl[i + 1].ToLower() == "products")
{
if ((i + 2) < strUrl.Length)
ProductCode = strUrl[i + 2];
if ((i + 3) < strUrl.Length)
Size = strUrl[i + 3];

string serverDirectory = app.Server.MapPath("~/UploadImages/" + Size);
string FilePath = System.IO.Path.Combine(serverDirectory, ProductCode) + ".jpg";
//app.Server.Transfer("~/ImageSystem/RetreiveImages.aspx?productcode=" + ProductCode + "&size=" + Size + "",false);
// app.Response.Redirect ("~/UploadImages/" + Size + "/" + ProductCode + ".jpg");

byte[] photo = null;
if (System.IO.File.Exists(FilePath))
{
photo = ReadImage(app.Server.MapPath( "~/UploadImages/" + Size + "/" + ProductCode + ".jpg"));//FilePath;
}
else
{
photo = ReadImage(app.Server.MapPath("~/UploadImages/" + Size + "/Missing.jpg"));//FilePath;

}
if (photo != null)
{
app.Response.ContentType = "image/jpeg";
app.Response.Cache.SetCacheability(HttpCacheability.Public);
app.Response.BufferOutput = false;
app.Response.OutputStream.Write(photo, 0, photo.Length);
}






}
}
// app.Response.Write(ProductCode+" hi "+ Size);

}

public void Dispose()
{
}
private static byte[] ReadImage(string p_postedImageFileName)
{
// bool isValidFileType = false;
try
{
FileInfo file = new FileInfo(p_postedImageFileName);


FileStream fs = new FileStream(p_postedImageFileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] image = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
return image;

// return null;
}
catch (Exception ex)
{
return null;
//throw ex;
}
}
}

Web.Config settings
register http module



1 comment:

dips said...

Hi.. its realy good and helpfull.
Deepak Mitawa