<%@ WebHandler Language="C#" Class="TextHandler" %> /* Copyright (c) 2005 Eric W. Bachtal Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------- http://ewbi.blogs.com/develops/2005/11/aspnet_dynamic_.html */ using System; using System.IO; using System.Net; using System.Web; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Text; using System.Runtime.InteropServices; public class TextHandler : IHttpHandler { const string VERSION = "1.0"; MemoryStream PlotText(string text) { try { string fontFamily = GetArg("family", "Verdana"); float fontSize = float.Parse(GetArg("size", "12")); // assumed to be pixels bool fontBold = bool.Parse(GetArg("bold", "false")); bool fontItalic = bool.Parse(GetArg("italic", "false")); bool fontUnderline = bool.Parse(GetArg("underline", "false")); Color fontColor = GetColor(GetArg("color", "Black")); // arbitrary limits to avoid killing my servers; feel free to change in your own implementation if (text.Length > 100) text = text.Substring(0, 100); if (fontSize > 400) fontSize = 400; // need a bitmap and graphics object in order to measure the text to determine the height and width // of the actual bitmap and graphics objects. SizeF size = new SizeF(1, 1); Font font = null; try { using (Bitmap bitmap = new Bitmap(1, 1)) { using (Graphics g = Graphics.FromImage(bitmap)) { g.TextRenderingHint = TextRenderingHint.AntiAlias; FontStyle fontStyle = FontStyle.Regular; if (fontBold) fontStyle |= FontStyle.Bold; if (fontItalic) fontStyle |= FontStyle.Italic; if (fontUnderline) fontStyle |= FontStyle.Underline; font = new Font(fontFamily, fontSize, fontStyle, GraphicsUnit.Pixel); // could get fancy here with StringFormat options size = g.MeasureString(text, font); } } using (Bitmap bitmap = new Bitmap((int)size.Width, (int)size.Height, PixelFormat.Format32bppArgb)) { using (Graphics g = Graphics.FromImage(bitmap)) { using (SolidBrush br = new SolidBrush(Color.White)) { g.FillRectangle(br, 0, 0, bitmap.Width, bitmap.Height); } using (SolidBrush br = new SolidBrush(fontColor)) { g.DrawString(text, font, br, 0, 0); } MemoryStream m = new MemoryStream(); bitmap.Save(m, ImageFormat.Gif); return MakeTransparent(m); } } } finally { if (font != null) font.Dispose(); } } catch { return PlotError(); } } MemoryStream PlotError() { MemoryStream m = new MemoryStream(); using (Bitmap bitmap = new Bitmap(40, 15, PixelFormat.Format32bppArgb)) { using (Graphics g = Graphics.FromImage(bitmap)) { using (SolidBrush br = new SolidBrush(Color.White)) { g.FillRectangle(br, 0, 0, bitmap.Width, bitmap.Height); } using (Pen p = new Pen(Color.Red)) { g.DrawLine(p, 0, 0, bitmap.Width, bitmap.Height); g.DrawLine(p, 0, bitmap.Height, bitmap.Width, 0); } bitmap.Save(m, ImageFormat.Gif); } } return MakeTransparent(m); } void ok() { SetResponse(HttpStatusCode.OK, "Ok"); } void error() { error(HttpStatusCode.BadRequest, "Bad Request"); } void error(HttpStatusCode statusCode, string statusDescription) { SetResponse(statusCode, statusDescription); _response.BinaryWrite(PlotError().ToArray()); _response.End(); } HttpRequest _request; HttpResponse _response; public void ProcessRequest(HttpContext context) { _request = context.Request; _response = context.Response; if (!(("GET" == _request.RequestType) || ("HEAD" == _request.RequestType))) error(HttpStatusCode.MethodNotAllowed, "Method Not Allowed"); string text = GetArg("text", ""); if (text.Length == 0) error(); ok(); _response.BinaryWrite(PlotText(text).ToArray()); } public bool IsReusable { get { return false; } } // -------------------------------------------------------------------- string GetArg(string argName, string argDefault) { string arg = _request.QueryString[argName]; if ((null == arg) || (arg.Length == 0)) return argDefault; return arg; } void SetResponse(HttpStatusCode statusCode, string statusDescription) { _response.ContentType = "image/gif"; _response.StatusCode = (int) statusCode; _response.StatusDescription = statusDescription; _response.AddHeader("ETag", ((string) (_request.QueryString.ToString() + VERSION)).GetHashCode().ToString()); _response.Flush(); } Array Redim(Array origArray, int newSize) { Type t = origArray.GetType().GetElementType(); Array newArray = Array.CreateInstance(t, newSize); Array.Copy(origArray, 0, newArray, 0, Math.Min(origArray.Length, newSize)); return newArray; } Color GetColor(string color) { if (color.StartsWith("#")) { return Color.FromArgb(IntFromHexRgbPart(color, RgbPart.RgbPartRed), IntFromHexRgbPart(color, RgbPart.RgbPathGreen), IntFromHexRgbPart(color, RgbPart.RgbPartBlue) ); } return Color.FromName(color); } enum RgbPart { RgbPartRed, RgbPathGreen, RgbPartBlue }; int IntFromHexRgbPart(string hexRgb, RgbPart part) { if ((null == hexRgb) || (hexRgb.Length == 0) || (!(hexRgb.StartsWith("#")))) return 0; try { switch (part) { case RgbPart.RgbPartRed: if (hexRgb.Length < 3) return 0; return IntFromHex(hexRgb.Substring(1, 2)); case RgbPart.RgbPathGreen: if (hexRgb.Length < 5) return 0; return IntFromHex(hexRgb.Substring(3, 2)); case RgbPart.RgbPartBlue: if (hexRgb.Length < 7) return 0; return IntFromHex(hexRgb.Substring(5, 2)); default: return 0; } } catch { return 0; } } int IntFromHex(string hex) { return (int) byte.Parse(hex, System.Globalization.NumberStyles.HexNumber); } MemoryStream MakeTransparent(MemoryStream origBitmapMemoryStream) { Color transparentColor = GetColor("White"); int transparentArgb = transparentColor.ToArgb(); using (Bitmap origBitmap = new Bitmap(origBitmapMemoryStream)) { using (Bitmap newBitmap = new Bitmap(origBitmap.Width, origBitmap.Height, origBitmap.PixelFormat)) { ColorPalette origPalette = origBitmap.Palette; ColorPalette newPalette = newBitmap.Palette; int index = 0; int transparentIndex = -1; foreach (Color origColor in origPalette.Entries) { newPalette.Entries[index] = Color.FromArgb(255, origColor); if (origColor.ToArgb() == transparentArgb) transparentIndex = index; index += 1; } if (-1 == transparentIndex) { return origBitmapMemoryStream; } newPalette.Entries[transparentIndex] = Color.FromArgb(0, transparentColor); newBitmap.Palette = newPalette; Rectangle rect = new Rectangle(0, 0, origBitmap.Width, origBitmap.Height); BitmapData origBitmapData = origBitmap.LockBits(rect, ImageLockMode.ReadOnly, origBitmap.PixelFormat); BitmapData newBitmapData = newBitmap.LockBits(rect, ImageLockMode.WriteOnly, newBitmap.PixelFormat); for (int y = 0; y < origBitmap.Height; y++) { for (int x = 0; x < origBitmap.Width; x++) { byte origBitmapByte = Marshal.ReadByte(origBitmapData.Scan0, origBitmapData.Stride * y + x); Marshal.WriteByte(newBitmapData.Scan0, newBitmapData.Stride * y + x, origBitmapByte); } } newBitmap.UnlockBits(newBitmapData); origBitmap.UnlockBits(origBitmapData); MemoryStream m = new MemoryStream(); newBitmap.Save(m, ImageFormat.Gif); return m; } } } }