FOLLOW US
softpcapps Software CODE HELP BLOG

Shareware and free Open Source Windows Software Applications and free Online Tools

How to Draw on an existing or new Image

How to Draw on a New Image

To draw on an Image we have get its Graphics object. For example if we have a Bitmap called bmp then we have to use the method Graphics.FromImage to get its graphics object.
	
 
 int iwidth=300;
 int iheight=300;
 
 Bitmap bmp=new Bitmap(iwidth,iheight);
 
 using (Graphics g=Graphics.FromImage(bmp))
 {
	 // drawing stuff
 }
 

Then we can start drawing on the image with the various graphics methods such as FillRectangle, DrawString, DrawLine e.t.c.
You can also clear the image contents in the beginning with the Clear method of the graphics object that accepts the desired background color value.
	
 
	using (Graphics g = Graphics.FromImage(bmp))
	{
		g.Clear(Color.LightGray);
		
		g.DrawLine(Pens.Black, 0, 0, 300, 300);

		g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

		g.DrawString("hello world", this.Font, Brushes.Black, 50f, 50f);		
	}

How to Draw on an existing Image

To draw on an existing image we do something similar to above but instead of creating a new bitmap we load the existing image.
We also do not clear the image in the beginning because that would erase it existing contents.
For example :
	
 
// image's filepath
string filepath=@"c:\images\myimage.png";

Bitmap bmp = new Bitmap(filepath);

	using (Graphics g = Graphics.FromImage(bmp))
	{					
		g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

		g.DrawString("hello world", this.Font, Brushes.Black, 50f, 50f);		
	}

How to save changes we did on the Image

Now to save the changes we made we simply save it like following :
	

 // new image filepath
 
 string newfilepath=@"c:\images\myimagenew.png";
 
 // we save the bitmap as an PNG image
 
 bmp.Save(newfilepath,System.Drawing.Imaging.ImageFormat.Png);