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.
- So the method takes the image and the HttpContext
- It sets the response type to image/png, you could also set the response type to other types of images.
- Next I new up a memory stream and then save the image into the memory stream with the ImageFormat set to Png
- Then I call dispose on the image class to make sure it doesn’t hang around eating up resources.
- 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
- 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)
- Also the size of the font, as well as the color to be used for the text.
- Next I specify the format of the text and set the text that will be generated
- Then I specify the starting point of the text
- Finally I create a new Bitmap with a width and height
Drawing The Text
- The code starts by taking the bitmap created earlier to be used as the “canvas” for the drawing
- The method call to Clear setting the background to white
- Next the SmoothingMode is set to AntiAlias
- A GraphicsPath is instantiated, this is the path of the text to be drawn.
- Now the Pen object is created to hold the color that will be used to draw the outline of the text.
- The method call to DrawPath with the path of the text passed and the pen with the outline color set.
- Now a new brush for the main text is created.
- Then the path is filled with the main color.
- The objects that implement IDisposable are passed to a method that disposes them.
- The graphic object has it’s save method called that generates the image in the bitmap that was passed
- Finally the graphic is written to the response.
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.