Read image from database and write to file
<%@ WebHandler Language="C#" Class="ImageVender" %>
using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Drawing;
public class ImageVender : IHttpHandler
{
private HttpContext context;
private string folderPath;
private string table = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("ImageAlbum"));
public void ProcessRequest(HttpContext context)
{
folderPath = string.Format("{0}{1}", context.Request.Url.AbsolutePath.Replace("ImageVender.ashx", ""), table);
this.context = context;
if (string.IsNullOrEmpty(context.Request.QueryString["id"]))
{
//context.Response.StatusCode = 404;
context.Response.ContentType = "text/plain";
context.Response.Write("Can't find the picture.");
context.Response.End();
}
else
{
bool resized = !string.IsNullOrEmpty(context.Request.QueryString["r"]);
string url = FindImage(context.Request.QueryString["id"], resized);
if (url == string.Empty)
{
LoadImageData();
context.Response.Redirect(FindImage(context.Request.QueryString["id"], resized));
}
else
{
if (context.Request.Headers["ImageOperation"] == "RmoveImageFile")
{
try
{
string file = context.Server.MapPath(FindImage(context.Request.QueryString["id"], true));
if (File.Exists(file))
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
}
catch { }
try
{
string file = context.Server.MapPath(FindImage(context.Request.QueryString["id"], false));
if (File.Exists(file))
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
}
catch { }
//LoadImageData();
//context.Response.Redirect(FindImage(context.Request.QueryString["id"], resized));
}
else
{
context.Response.Redirect(url);
}
}
}
}
private string FindImage(string id, bool resized)
{
string path = string.Format("{0}/{1}{2}.", folderPath, (resized ? "r" : ""), id);
if (File.Exists(context.Server.MapPath(path + "jpg"))) return path + "jpg";
if (File.Exists(context.Server.MapPath(path + "bmp"))) return path + "bmp";
if (File.Exists(context.Server.MapPath(path + "gif"))) return path + "gif";
if (File.Exists(context.Server.MapPath(path + "png"))) return path + "png";
return string.Empty; ;
}
private void LoadImageData()
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[VarHelper.ConnStrLocal].ConnectionString))
{
SqlCommand cmd = new SqlCommand("SELECT [MimeType], [Image], [UpdateTime] FROM [ImageAlbum] WITH (NOLOCK) WHERE [ImageID] = @ImageID", conn);
cmd.Parameters.Add("@ImageID", System.Data.SqlDbType.Int).Value = context.Request.QueryString["id"];
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
byte[] data = null;
string contentType = string.Empty;
DateTime updateTime = DateTime.Now;
while (reader.Read())
{
data = (byte[])reader["Image"];
contentType = (string)reader["MimeType"];
updateTime = (DateTime)reader["UpdateTime"];
}
WriteImageFile(context.Server.MapPath(folderPath), ConcatFileName(context.Request.QueryString["id"], contentType), data);
//context.Response.ContentType = contentType;
//context.Response.BinaryWrite(data);
//context.Response.End();
}
else
{
context.Response.StatusCode = 404;
}
conn.Close();
}
}
private string ConcatFileName(string id, string mimeType)
{
switch (mimeType)
{
case "image/x-png":
return string.Format("{0}.png", id);
case "image/pjpeg":
return string.Format("{0}.jpg", id);
case "image/gif":
return string.Format("{0}.gif", id);
case "image/bmp":
return string.Format("{0}.bmp", id);
default:
return string.Empty;
}
}
private void WriteImageFile(string path, string filename, byte[] data)
{
//string folder = context.Server.MapPath(path);
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
string file = string.Format("{0}\\{1}", path, filename);
File.WriteAllBytes(file, data);
Image source = Image.FromFile(file);
if (source.Width > 150 || source.Height > 150)
{
double resizeWidth = 150.0 / source.Width * 100;
double resizeHeight = 150.0 / source.Height * 100;
Image resized = null;
if (resizeWidth > resizeHeight)
{
resized = ImageResizer.ScaleByPercent(source, (int)resizeHeight);
}
else
{
resized = ImageResizer.ScaleByPercent(source, (int)resizeWidth);
}
resized.Save(string.Format("{0}\\r{1}", path, filename));
}
else
{
source.Save(string.Format("{0}\\r{1}", path, filename));
}
}
public bool IsReusable
{
get
{
return false;
}
}
}