this blog contains information for .net and sql stuffs. You can find various tips and tricks to overcome problem you may be facing in ...

Tuesday, May 25, 2010

Graphics with .net (Part -2)

As we discussed in previous post, we required to modify existing image file or have to create new image, chart, edit image and back save to file.

Image and Bitmap class provides ability to modify existing image file or create new image file.

Image is an abstract class, but we can have instance of it by Image.FromFile or Image.FromStream methods. FromFile accept any image file, FromStream accepts stream of Image file. We can use whatsoever we have at hand when we are going to play with Image.

Bitmap class is inherited by Image, For still image we can use Bitmap class, For animated image we can use System.Drawing.Imaging.MetaFile. Bitmap class is widely used for image editing and creation compared to MetaFile.

Display Image in background.
To display image in the back ground of form or any control we have one or more techniques, we can choose any of them.

Take a picturebox control on the form, or create instance of picture box and set BackGroundImage property.

Image backImage = Image.FromFile(“@myImage.jpg”);
myPictureBox.BackGroundImage = backImage;

Here we have placed picturebox control and set its name myPictureBox. myImage.jpg is file available in our current directory else we can specify whole path of my image file.

In another method, we can set background image using Graphics.DrawImage method.

Bitmap backImage = new Bitmap(“@myImage.jpg”);
Graphics g = this.CreateGraphics();
g.DrawImage(backImage,1,1,this.Width,this.Height);

DrawImage methods has 30 around overloaded method, we can use any of them.

Create and Save Image

To create or edit any image first create object of Bitmap class, edit it using Graphics then with Bitmap.Save method, save it back to disk.

Bitmap bm = new Bitmap(600, 600);
Graphics g = Graphics.FromImage(bm);

Brush b = new LinearGradientBrush(new Point(1, 1), new Point(600, 600), Color.White, Color.Blue);

Point[] points = new Point[] {new Point(10, 10), new Point(77, 500), new Point(590, 100), new Point(250, 590), new Point(300, 410)};
g.FillPolygon(b, points);
bm.Save("bm.jpg", ImageFormat.Jpeg);

In above code we have created a polygon and filled it with Blue-while Gradient Brush. Once it done, we save it to disk by bm.jpg to our current directory.

To edit an image, just use another over load of Bitmap constructor that takes file as parameter.

Display Icon
Icon are transparent bitmap image with specific size and used to convey status to windows system. .Net have provided built in Icons with 40-40 size for Questions, Exclamation, Information etc.

To add Icon to Form or control just call Graphics.DrawIcon method, it will do rest for us.

Graphics g = this.CreateGraphics();
g.DrawIcon(SystemIcons.Information, 40, 40);

Above code will draw 40*40 Information Icon on our form.

No comments: