Friday, December 12, 2008

Watermark on image : Draw string on the image

·

Page Load event

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
AddWatermark("Demo version");
// Add watermark with "Demo version" text
}
}

Method to add WaterMark text on the image

public void AddWatermark(string watermarkText)
{
// get image from specific path
System.Drawing.Image bitmap = (System.Drawing.Image)Bitmap.FromFile(Server.MapPath("1.jpg"));


Font font = new Font("Arial", 20, FontStyle.Bold, GraphicsUnit.Pixel);

Color color = Color.FromArgb(255, 255, 0, 0);
//Adds a red watermark with.

Point atPoint = new Point(bitmap.Width/2, bitmap.Height/2);
//The pixel point to draw the watermark at (this example puts it at center point (x, y)).

SolidBrush brush = new SolidBrush(color);

Graphics graphics = Graphics.FromImage(bitmap);

StringFormat sf=new StringFormat();
sf.Alignment= StringAlignment.Center;
sf.LineAlignment= StringAlignment.Center;
// String Format to draw string at center point

graphics.DrawString(watermarkText, font, brush, atPoint,sf);
// Draw string on image

graphics.Dispose();
MemoryStream m = new MemoryStream();
bitmap.Save(m,System.Drawing.Imaging.ImageFormat.Jpeg);
m.WriteTo(Response.OutputStream);
m.Dispose();
base.Dispose();

}

0 comments: