Click here to Skip to main content
13,357,514 members (72,817 online)
Click here to Skip to main content
Add your own
alternative version


14 bookmarked
Posted 3 Jun 2012

Run-time Image in ASP.NET using GDI+

, 12 Jun 2012
Rate this:
Please Sign up or sign in to vote.
How to make a dynamic/embedded image at run-time for an ASP.NET application using GDI+.

Sample Image


This tip explains how to make a dynamic/embedded image at run-time for an ASP.NET application using GDI+.


I searched around in Google and the only answer I could find was to make an ASPX page, hijack the Response.OutputStream, and change the Response.ContentType. This approach I think is far easier to work with, although older browser compatibility issues may come into play. Read about embedded image data and dataURI here: Wiki - Data_URI_scheme. There is also a Microsoft disclaimer for using GDI+ within ASP.NET. Anyway...

Using the code

Here is the code for the ASP.NET 'UserControl'. There is no mark-up code, and below is the code-behind.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.IO;

public partial class UserControls_ImageRender : System.Web.UI.UserControl

    protected override void Render(HtmlTextWriter writer)
        writer.Write(@"<img src=""data:image/jpeg;base64,{0}"">", Data64);

    public Bitmap bitmap
            MemoryStream ms = new MemoryStream();
            value.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            Data64 = Convert.ToBase64String(ms.ToArray());

    private string Data64
            string s = ViewState["Data64"] as string;
            return (s == null) ? string.Empty : s;
        { ViewState["Data64"] = value; }

Register your control in web.config:

<add tagPrefix="ctl" src="~/UserControls/ImageRender.ascx" tagName="ImageRender"/>

Add an example to use on your form:

<ctl:ImageRender id="Image1" runat="server"/>

Use this Control, by setting the bitmap property.

protected void Page_Load(object sender, EventArgs e)
    if (!IsPostBack)
        Image1.bitmap = MakeImage();
// make your own GDI+ image here. Here is my example...
public Bitmap MakeImage()
    DateTime dt = DateTime.Now;
    string sHeading1 = "asd";
    string sMachineSerial = "asdasd";
    string sText1 = "rtu";
    string sText2 = "uiouiouio";
    string sText3 = "dfgbftyfy";

    Bitmap bitmap = new System.Drawing.Bitmap(400, 200);
    Graphics g = System.Drawing.Graphics.FromImage(bitmap);
    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
    g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

    System.Drawing.Font drawFontAGBoldSmall = new System.Drawing.Font("Arial", 8);
    System.Drawing.Font drawFontAGBold = new System.Drawing.Font("Arial", 12);
    System.Drawing.Font drawFontAGBook = new System.Drawing.Font("Arial", 12, FontStyle.Bold);
    System.Drawing.Font drawFontAGBookDate = new System.Drawing.Font("Arial", 24);
    System.Drawing.Font drawFontAGBookHeading = new System.Drawing.Font("Arial", 16, FontStyle.Bold);
    System.Drawing.Font drawFontArial = new System.Drawing.Font("Arial", 12, FontStyle.Bold);

    Color myColor = ColorTranslator.FromHtml(@"#F0F0F0");
    System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(myColor);

    System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat();
    System.Drawing.StringFormat drawCentreFormat = 
           new System.Drawing.StringFormat(StringFormatFlags.NoWrap);
    drawCentreFormat.Alignment = StringAlignment.Center;

    Pen drawPen = new Pen(drawBrush);

    g.DrawRectangle(drawPen, new Rectangle(0, 0, bitmap.Width - 1, bitmap.Height - 1));

    g.DrawString(dt.ToShortDateString(), drawFontAGBookDate, drawBrush, 
                 new Rectangle(0, 36, 400, 40), drawCentreFormat);
    g.DrawString(sHeading1, drawFontAGBookHeading, drawBrush, new Rectangle(4, 0, 392, 26), drawFormat);
    g.DrawString(sMachineSerial, drawFontAGBoldSmall, drawBrush, new Rectangle(8, 22, 392, 14), drawFormat);
    g.DrawString(sText1, drawFontAGBold, drawBrush, new Rectangle(8, 80, 192, 20), drawFormat);
    g.DrawString(sText2, drawFontAGBold, drawBrush, new Rectangle(8, 101, 192, 20), drawFormat);
    g.DrawString(sText3, drawFontAGBold, drawBrush, new Rectangle(8, 122, 192, 20), drawFormat);


    return bitmap;


All done! As my son would write, thanks for listening!


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Richard Leiser
Web Developer
Switzerland Switzerland
No Biography provided

You may also be interested in...


Comments and Discussions

QuestionMessage Closed Pin
21-Dec-14 21:50
memberpaul000921-Dec-14 21:50 
GeneralBase64 vs. Content-type Pin
Enigmatic Texan21-Jun-12 10:17
memberEnigmatic Texan21-Jun-12 10:17 
QuestionI wont vote but: Pin
HaBiX14-Jun-12 21:12
memberHaBiX14-Jun-12 21:12 
AnswerRe: I wont vote but: Pin
Richard Leiser14-Jun-12 23:49
memberRichard Leiser14-Jun-12 23:49 
GeneralRe: I wont vote but: Pin
HaBiX15-Jun-12 0:01
memberHaBiX15-Jun-12 0:01 
GeneralRe: I wont vote but: Pin
Richard Leiser15-Jun-12 4:17
memberRichard Leiser15-Jun-12 4:17 
GeneralRe: I wont vote but: Pin
HaBiX15-Jun-12 7:15
memberHaBiX15-Jun-12 7:15 
My mistake for base64, but it still makes files bigger by 33%.

Ok, the sample I provided didn't have all the candy, but consider this style of functions:
Image1.Src = CreateBitmapUrl(TextBoxProductWidth.Text, TextBoxProductHeight.Text, TextBoxProductLength.Text); //which in fact generates a querystring

the other way (if you already got a bitmap object on page context):

Bitamp bitmap = GetAnyPicReally();

Image1.Src = MyImageManager.GenerateUrlForBitmap(bitmap); //image manager passes bitmap object to HttpContext.Current.Items["someguid"], (can be db, file, server cache, etc), the page that sends the bitmap data, simply picks the item from HttpContext.Current.Items, flushed to response buffer and clears it.

About cache & qerystring:

Client will make cache itmes based on querystring, so: DynamicPictureGenerator.aspx?say=hello%20world & DynamicPictureGenerator.aspx?say=hi will be stored in cache as 2 separate images. If the image can change based on other parameters (like if you want to draw time on image) you can still send cache expires via http headers.
Generalsome great feedback Pin
Richard Leiser15-Jun-12 14:14
memberRichard Leiser15-Jun-12 14:14 
GeneralRe: some great feedback Pin
HaBiX17-Jun-12 21:31
memberHaBiX17-Jun-12 21:31 
GeneralMy vote of 5 Pin
Carsten V2.05-Jun-12 5:26
memberCarsten V2.05-Jun-12 5:26 
Questionhello Pin
beleshi4-Jun-12 0:44
memberbeleshi4-Jun-12 0:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.180111.1 | Last Updated 12 Jun 2012
Article Copyright 2012 by Richard Leiser
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid