HOW TO generate an image dynamically with ASP.Net

GDI is a Microsoft Windows standard for representing graphical objects and transmitting them to output devices such as monitors and printers.

GDI+ is a wrapper-library for traditional GDI.

Unlike GDI, GDI+ text layout is resolution independent
, and forms built with GDI+ text look the same at all resolutions and when printed

This nifty snippet places text dynamically on an image using GDI+ in ASP.NET. View the output first and change the querystring value to notice how neat it is.


1<%@ OutputCache Duration="500" VaryByParam="Text" %>
2<%@ Page Language="C#" trace="false" Explicit="true" aspcompat="true" Debug="true" %>
3<%@ Import Namespace="System" %>
4<%@ Import Namespace="System.IO" %>
5<%@ Import Namespace="System.Text" %>
6<%@ Import Namespace="System.Drawing" %>
7<%@ Import Namespace="System.Drawing.Imaging" %>
8<%@ Import Namespace="System.Drawing.Text" %>
9<%@ Import Namespace="System.Drawing.Drawing2D" %>
10
11 script runat="server">
12 private void Page_Load(object sender, System.EventArgs e)
13 {
14 Bitmap bitmap = new Bitmap(Server.MapPath("josh.bmp"));
15 MemoryStream memStream = new MemoryStream();
16
17 // generate image
18
19 // Create a graphics object for drawing.
20 Graphics g = Graphics.FromImage(bitmap);
21 g.SmoothingMode = SmoothingMode.AntiAlias;
22
23 int width = bitmap.Width;
24 int height = bitmap.Height;
25
26 string familyName = "Tahoma";
27 string text = Request.Params["Text"];
28
29 // get a rectangle on his shirt
30 Rectangle rect = new Rectangle(150, 216, 210, 135);
31
32 // Set up the text font.
33 Font font;
34 font = new Font(familyName, 16F, FontStyle.Regular);
35
36 // Set up the text format.
37 StringFormat format = new StringFormat();
38 format.Alignment = StringAlignment.Center;
39 format.LineAlignment = StringAlignment.Center;
40
41 // Create a path using the text and warp it to fit over his contour
42 GraphicsPath path = new GraphicsPath();
43 path.AddString(text, font.FontFamily, (int) font.Style, font.Size, rect, format);
44
45 PointF[] points =
46 {
47 new PointF(rect.X - 10, rect.Y - 8),
48 new PointF(rect.X + rect.Width - 20, rect.Y + 4),
49 new PointF(rect.X - 8, rect.Y + rect.Height - 15),
50 new PointF(rect.X + rect.Width - 10, rect.Y + rect.Height + 4)
51 };
52 Matrix matrix = new Matrix();
53 matrix.Translate(0F, 0F);
54 path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);
55
56 // Draw the text.
57 HatchBrush hatchBrush = new HatchBrush(
58 HatchStyle.LargeConfetti,
59 Color.LightGray,
60 Color.DarkGray);
61
62 g.FillPath(hatchBrush, path);
63
64 Response.Clear();
65 Response.ContentType="image/jpeg";
66 bitmap.Save(memStream, ImageFormat.Jpeg);
67 memStream.WriteTo(Response.OutputStream);
68
69 // Clean up.
70 font.Dispose();
71 hatchBrush.Dispose();
72 g.Dispose();
73 bitmap.Dispose();
74
75 }
76
77/script>

Comments