Dynamically Creating Image in C#.Net

        As per the requirement from one of my client, an image should be generated dynamically by taking the necessary information from the user.  When I went on a search, I came to know that, my crazy DotNet framework provided my two namespaces System.Drawing and System.Drawing.Imaging.  It’s enough to learn three classes from these namespaces - Bitmap and Graphics for generating an image dynamically related to System.Drawing Namespace and FileFormat class is for saving the created image in different file formats and is related to System.Drawing.Imaging Namespace.

            Bitmap class is useful to generate a new image and to save it different file formats.  Graphics class is useful to design the image using lines, curves, rectangles, text etc., with colors and everything.  FileFormat class is useful to save the file in a particular or in different formats like Jpeg, Png, Bmp etc.  The default format is png.
            Now lets jump into code.  After declaring namespaces, we need to create an image with bitmap class as follows.
Bitmap bmp = new Bitmap(200, 200);

Here bmp is the image with the height 200 and width 200.  Next we need to create a Graphics Object for our bmp Image as follows.
Graphics gr;
gr = Graphics.FromImage(bmp);

That’s it you have created image successfully with a little bit of graphics.  Now you have to go through the Graphics class for more manipulations of the image like drawing lines, rectangles, creating text etc., some examples as follows
For giving background color for image:

For drawing line:
gr.DrawLine(new Pen(Color.Black), 0, 0, 100, 0); 

for Writing text in image:
gr.DrawString("dileepKumar", objFont, new SolidBrush(Color.Black), 0, 0);

After finishing designing the image, you have to save the image in your desired format will be as follows,

After saving the image you need to dispose the Bitmap Object and Graphics Object.

Now your image is successfully generated with your graphical stuff which you have provided using the graphics object.

Any Queries or Comments are good to hear…

--Happy Programming


Post a Comment

Popular posts from this blog


Data Table Vs List