ast issue’s article, “Using GDI+ in ASP.NET Web Applications, Part 1“, introduced basic concepts for generating images dynamically to use on Web pages. Keep in mind that the fundamental steps include: generation of in-memory Bitmap objects, drawing using the GDI+ API, and streaming the binary result back to the client (browser) using the ASP.NET OutputStream object.
In the last issue, I investigated GDI+ and how to use it for image manipulation in Web applications. This time around, I will look at the generation of brand new images using the same GDI+ technology and features.
The techniques demonstrated in this second article are very similar. The main difference lies in the in-memory Bitmap on which you will draw. Although in the previous article you started out with an existing image, in this article I’ll show you how to draw on a completely blank image, generated from scratch.
A Text Example
To start out I’ll show you how to generate text output.
One task that is generally tricky on Web pages (especially in a browser-neutral environment) is displaying drop caps (see Figure 1 for an example, and the sidebar called “Drop Caps” for more information). This is a very widely used technique in other publishing environments, but in HTML, there is no native way to produce them. For this reason, most Web sites that use drop caps generate (static) images for the utilized letters. Using GDI+ you can make this task straightforward and dynamic.
|A Text Example (continued)
The MeasureFont() method returns a SizeF object. This object has two properties you are interested in: The height and the width. Note that you are not just retrieving these values and accepting them as they are. Instead, reduce the height and increase the width of the required space. There is a good reason to do that. For one, you want to render a slight shadow for the font. This requires the output area to be slightly larger as the shadow will be offset to the right and the bottom of the image. Also, drop caps are always upper-case characters. The MeasureFont() method retrieves fundamental measurements of the passed character, and that includes under lengths as they occur in some lower-case letters, such as “g,” “y,” and the like, despite the fact that your chosen character does not have under lengths. (The height for every character in a certain font is always the same.) Because you are not interested in providing space for those under lengths, subtract 10 pixels from the returned values. (Note that this is a somewhat lazy approach. You could have also calculated the correct under length on the fly rather than hard-coding it.)