Generating Images With .Net Part 1

I’ve recently had a project that required a great deal of image generation and manipulation. Not having done image manipulation in a good long while I thought it would be good to capture some of the “tricks of the trade”. One of the things I noticed in my searching for information on generating images in .Net is how bad variables were named. Hungarian notation or single letter names. This is not cool so I’m going to be trying to use descriptive names for all of my variables.

In this post I’ll cover how to display an image via the HttpResponse and then to generate an image from text.

Displaying Any Image

The following Code will write out the image to the HttpResponse in order for it to be displayed.

   1: protected void WriteImageToResponse(HttpContext context, Image imageToServe)
   2: {
   3:     context.Response.ContentType = "image/png";
   4:     using (MemoryStream memStream = new MemoryStream())
   5:     {
   6:         imageToServe.Save(memStream, ImageFormat.Png);
   7:         imageToServe.Dispose();
   8:         memStream.WriteTo(context.Response.OutputStream);
   9:         memStream.Dispose();
  10:     }
  11: }
  1. So the method takes the image and the HttpContext
  2. It sets the response type to image/png, you could also set the response type to other types of images.
  3. Next I new up a memory stream and then save the image into the memory stream with the ImageFormat set to Png
  4. Then I call dispose on the image class to make sure it doesn’t hang around eating up resources.
  5. Next the WriteTo method of the memory stream

Generating a Text Image

The following code sample will show how to generate an image from a text with an outline.

Setting the stage

   1: var fontCollection = new PrivateFontCollection();
   2: var fontSize = 72.0f;
   3: var fontLocation = "fonts/BIRDMAN_.ttf"; 
   4: fontCollection.AddFontFile(context.Server.MapPath(fontLocation));
   5: SolidBrush colorBrushForText = new SolidBrush(ColorTranslator.FromHtml("#567DB6"));
   6: StringFormat formatOfText = StringFormat.GenericTypographic;
   7: string textToDraw = "Hello World";
   8: var startingPointForText = new PointF(44, 20);
   9: var imageToRender = new Bitmap(600, 500);
  1. The code is setting up the Font from a location on the website (this is useful as you don’t need to install the font on the server)
  2. Also the size of the font, as well as the color to be used for the text.
  3. Next I specify the format of the text and set the text that will be generated
  4. Then I specify the starting point of the text
  5. Finally I create a new Bitmap with a width and height

Drawing The Text

   1: using (var masterGraphic = Graphics.FromImage(imageToRender))
   2: {
   3:     masterGraphic.Clear(Color.White);
   4:     masterGraphic.SmoothingMode = SmoothingMode.AntiAlias;
   5:     //uncomment the following line if you just want the text drawn
   6:     //masterGraphic.DrawString(textToDraw, fontToDraw, colorBrushForText, new PointF(xCoordinate, startingPointForText.Y), formatOfText);
   7:     GraphicsPath pathOfText = new GraphicsPath();
   8:     pathOfText.AddString(textToDraw, fontCollection.Families[0], (int)FontStyle.Regular, fontSize, startingPointForText, formatOfText);
   9:     Pen outlinePen = new Pen(Color.Black, 2);
  10:     masterGraphic.DrawPath(outlinePen, pathOfText);
  11:     SolidBrush solidBrushForText = new SolidBrush(ColorTranslator.FromHtml("#567DB6"));
  12:     masterGraphic.FillPath(solidBrushForText, pathOfText);
  13:     DisposeObjects(new List<IDisposable>{pathOfText,formatOfText,colorBrushForText, solidBrushForText,outlinePen});
  14:     masterGraphic.Save();
  15: }
  16: WriteImageToResponse(context, imageToRender);

  1. The code starts by taking the bitmap created earlier to be used as the “canvas” for the drawing
  2. The method call to Clear setting the background to white
  3. Next the SmoothingMode is set to AntiAlias
  4. A GraphicsPath is instantiated, this is the path of the text to be drawn.
  5. Now the Pen object is created to hold the color that will be used to draw the outline of the text.
  6. The method call to DrawPath with the path of the text passed and the pen with the outline color set.
  7. Now a new brush for the main text is created.
  8. Then the path is filled with the main color.
  9. The objects that implement IDisposable are passed to a method that disposes them.
  10. The graphic object has it’s save method called that generates the image in the bitmap that was passed
  11. Finally the graphic is written to the response.

The output


I hope this helps someone, and I hope it’s clear cut. In upcoming posts I’ll be explaining how to combine images, crop images and drawing shapes among other things.

kick it on

No Comments