wayne on January 29, 2008
Hmm, the magazine editor seemed to have left some code out of the February post of ASP.Net Pro. In Dino Esposito's article on how to serve up images on the web and with watermarks as well, the editor must have left some code out. I actually have a need for a solution like this and went through it. This is the corrected post, albeit untested. I suspect this is the editors fault only because the page looked tight with content and a little more room was needed. The page the code appears on seems pretty tight, and what was missing was superfluous to the intent of the article, so they probably ditched it.
Here's the corrected code (including the required using statements!):
using System;
using System.IO;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// process url param
object o1 = context.Request["url"];
if (o1 == null)
{
context.Response.End();
return;
}
string file = context.Server.MapPath((string)o1);
if (!IsImageFile(file))
{
context.Response.End();
return;
}
// read copyright string
string msg = "some copyright";
if (File.Exists(file))
{
Bitmap bmp = AddCopyright(file, msg);
context.Response.ContentType = "image/jpeg";
bmp.Save(context.Response.OutputStream, ImageFormat.Jpeg);
bmp.Dispose();
}
else
context.Response.End();
}
Bitmap AddCopyright(string file, string msg)
{
// load the file and create the graphics
Bitmap bmp = new Bitmap(file);
Graphics g = Graphics.FromImage(bmp);
// define text alignment
StringFormat strFmt = new StringFormat();
strFmt.Alignment = StringAlignment.Center;
// Create brushes for the bottom writing
// (green text on black background)
Font btmFont = new Font("Verdana", 7);
Brush btmForeColor = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
Brush btmBackColor = new System.Drawing.SolidBrush(System.Drawing.Color.White);
SizeF textSize = new SizeF();
textSize = g.MeasureString(msg, btmFont);
// Calc the output rectangle and fill
float x = ((float)bmp.Width - textSize.Width - 3);
float y = ((float)bmp.Height - textSize.Height - 3);
float w = ((float)x - textSize.Width);
float h = ((float)y - textSize.Height);
RectangleF textArea = new RectangleF(x, y, w, h);
g.FillRectangle(btmBackColor, textArea);
// draw the text and free resources
g.DrawString(msg, btmFont, btmForeColor, textArea);
btmForeColor.Dispose();
btmBackColor.Dispose();
btmFont.Dispose();
g.Dispose();
return bmp;
}
private static bool IsImageFile(string fileName)
{
return fileName.EndsWith(".jpg") ||
fileName.EndsWith(".gif") ||
fileName.EndsWith(".bmp");
}
public bool IsReusable
{
get { return true; }
}
}