Sunday, February 22, 2009

Useful Image WaterMark Extension Method

Today i'll give you a useful Extension Method in order to Add some Text to Image that can be used in HttpHandler to display copyrighted images from Database for a Photo Store for example.

WaterMarkImageHandler.ashx

Here is the Extension Code

public static Bitmap WaterMarkImage(this Bitmap bmp, String Text)
{
Image img = new Bitmap(bmp, new Size(bmp.Width, bmp.Height));
Bitmap tmp = new Bitmap(img);
using (Graphics graphic = Graphics.FromImage(tmp))
{
SolidBrush brush = new SolidBrush(Color.FromArgb(120, 255, 255, 255));
Font font = new Font("Arial", 18, FontStyle.Bold);
graphic.DrawString(Text, font, brush, new PointF(10, 30));
}
return tmp;
}
Here is a Sample of Usage
public class WaterMarkImageHandler : 
IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
Image img = Bitmap.FromFile(context.Server.MapPath("~/03SC008.JPG"));
Bitmap bmp = new Bitmap(img);
bmp = bmp.WaterMarkImage("SB2 DEVELOPPERS BLOG TEST");
bmp.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}

public bool IsReusable
{
get
{
return true;
}
}
}

Download Solution - WaterMarkImageHandler.zip

Source : http://blog.sb2.fr/post/2008/11/29/Useful-Image-WaterMark-Extension-Method.aspx

No comments:

Post a Comment