Creating a Bitmap Object

The Bitmap class provides about a dozen overloaded forms of the constructors. You can create a Bitmap object from a bitmap file, or from Image, Stream, string, or Type objects. When you create a Bitmap object, you can also specify the size of the bitmap, the resolution of the Graphics object, and the pixel format of the bitmap.

The code snippet in Listing 7.17 creates Bitmap objects from an Image and file name with or without the size of the Bitmap included.

Listing 7.17 Creating Bitmap objects from different sources
// Creating an Image object
Image curImage = Image.FromFile("myfile.gif");
// Creating a Bitmap object from a file name
Bitmap curBitmap1 = new Bitmap("myfile.gif");
// Creating a Bitmap object from an Image object
Bitmap curBitmap2 = new Bitmap(curImage);
// Creating a Bitmap object with size and image
Bitmap curBitmap3 =
new Bitmap(curImage, new Size(200, 100) );
// Creating a Bitmap object with no images
Bitmap curBitmap4 = new Bitmap(200, 100);

Besides the constructor, the Bitmap class provides two static methods—FromHicon and FromResource—which can be used to create a Bitmap object from a window handle to an icon and from a Windows resource (.res file), respectively.

7.5.2 Viewing a Bitmap

Viewing a bitmap using the Bitmap class is similar to viewing an image. After constructing a Bitmap object, you just pass it as a parameter to DrawImage. The following code snippet creates a Bitmap object from a file and views the bitmap by calling the DrawImage method of a Graphics object associated with a form. You can write this code on a menu or a button click event handler.

Graphics g = this.CreateGraphics();
Bitmap bitmap = new Bitmap("myfile.jpg");
g.DrawImage(bitmap, 20, 20);
g.Dispose();

+ Recent posts