Posts Tagged ‘ASP.NET’
ASP.NET – A Dynamic Image Server Control – Part 1
As you already know if you’re an ASP.NET developer, a server control renders pure HTML that is embedded into the page the server control is hosted. But what if you wanted to display a dynamic image on the page. Since the server control renders only HTML it would have to render some <img> tag pointing to some location on your web server or other. You could argue that instead of placing a custom made server control on the page just place an ASP.NET Image server control and target it appropriately. It could let’s say target an .aspx page that renders a dynamic image. But that just doesn’t feels right for a dynamic image. It’s not something some one can simply get out of the toolbox and drop it on the page in a nice componentized manner. Furthermore, customize it using the property editor and see how it looks even in design mode. That’s much better, but how?
Unfortunately, the answer is not so straightforward but for some things it can be. If you wanted to display let’s say a small image, for example a CAPTCHA, you could use the HTML URL scheme data:[<mediatype>][;base64],<data> that embeds the raw image data inside the page as Base64 characters:
1: protected override void RenderContents(HtmlTextWriter output)
2: {
3: using (Bitmap bitmap = new System.Drawing.Bitmap(40, 20))
4: {
5: using (Graphics graphics = System.Drawing.Graphics.FromImage(bitmap))
6: {
7: graphics.Clear(Color.Red);
8: graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
9: Font font = new Font("Arial", 8, FontStyle.Bold);
10: graphics.DrawString("HeLlo", font, Brushes.White, 3, 3);
11: output.Write(string.Format("<img src="data:image/png;base64,{0}">",
12: ImageToBase64(bitmap, ImageFormat.Png)));
13: }
14: }
15: }
16:
17: protected string ImageToBase64(System.Drawing.Image image, ImageFormat format)
18: {
19: using (MemoryStream ms = new MemoryStream())
20: {
21: // Convert Image to byte[]
22: image.Save(ms, format);
23: byte[] imageBytes = ms.ToArray();
24:
25: // Convert byte[] to Base64 String
26: return Convert.ToBase64String(imageBytes);
27: }
28: }
To be continued…