HOWTO: Draw your own string (URL, copyright) on each displayed picture in an ASP.NET website
By rickvdbosch
- 2 minutes read - 313 wordsThe AdRotator .NET provides can be used to show a different image each time a page is visited. You could write a webpage which does this for you, but it’s probably not very useful. Although you need to change the XML file when changing the images to be showed when you use an AdRotator, but that’s not the issue here.
Something .NET doesn’t deliver is a control to add your own text to an image when it is displayed on a webpage. And that’s exactly what we will be doing in this HowTo.
Below is the code I placed inside the page load of a webpage called showimg.aspx
. To display images with the text I want to print on them, you don’t use <IMG src=”test.jpg”/>
, but instead you use <IMG src=”showimg.aspx?image=test.jpg”/>
.
Please note: this code is illustrative. Normally you would perform a number of checks. For instance check if the querystring is filled, if the image exists, if the text will fit the image, and so on…
//Const declarations
const string outtext = “bloggingabout.net/rick”;
//Variable declarations
string img;
Image image;
Graphics graphics;
Font font;
SizeF textSize;
SolidBrush brush;
//Set font & brush and get image from QueryString
img = Request.QueryString[“image”];
font = new Font(“Verdana”, 9);
brush = new SolidBrush(Color.Black);
//Opening the specified image from the images folder
image = Image.FromFile(Server.MapPath(“images/” + img));
//Create graphics object for painting
graphics = Graphics.FromImage(image);
//Get the size the text will be with the defined font
textSize = graphics.MeasureString(outtext, font);
//Set SmoothingMode to AntiAlias
graphics.SmoothingMode = SmoothingMode.AntiAlias;
//Draw the string in the lower right corner of the image
graphics.DrawString(outtext, font, brush,
image.Width – textSize.Width,
image.Height – textSize.Height);
//Dispose used objects
graphics.Dispose();
font.Dispose();
brush.Dispose();
//Writing the image to the browser as the response:
//Set contenttype to image
Response.ContentType = “image/jpeg”;
//Save the changed image to response
image.Save(Response.OutputStream, ImageFormat.Jpeg);
//End repsone: it’s done 😉
Response.End();
//Dispose the image object
image.Dispose();