Home

Introduction to Bitmaps

 

Bitmaps Fundamentals

 

Introduction

A bitmap is a representation of a picture or another type of graphic on a window. For example, and as mentioned in the previous lesson, it can be used to show a regular picture on a form. Here is an example:

A bitmap can be used as a background for a window or a web page. A bitmap can also be used for an aesthetic purpose to decorate a dialog box. Thatís how it is used on some dialog boxes. Another regular use of bitmaps is as small graphics on toolbars:

Toolbar

Practical LearningPractical Learning: Introducing Bitmaps

  1. Start Microsoft Visual C++ 2005
  2. To start a new project, on the main menu, click File -> New -> Project... (or File -> New Project)
  3. In the Templates list, click Windows Forms Application and set the Name to PictureViewer1
  4. Click OK
  5. From the Toolbox, click Button and click the form
  6. While the button is still selected on the form, in the Properties window, change its characteristics as follows:
    Text: Open a Picture
    (Name): btnOpenPicture
     
  7. Right-click the form and click View Code
  8. Declare two global variables as follows:
     
    private:
    		/// <summary>
    		/// Required designer variable.
    		/// </summary>
    		System::ComponentModel::Container ^components;
    		bool PictureIsLoaded;
    		String ^ strPicture;
  9. Save the form

The Bitmap Class

To support bitmaps, the GDI+ library provides the Bitmap class. In the .NET Framework, the bitmap is represented by a class called Bitmap. The Bitmap class is derived from the Image abstract class. Both classes are defined in the System::Drawing namespace of the System.Drawing.dll assembly. The Bitmap class is serializable.

Getting a Bitmap

There are two primary ways you can get a bitmap to use in your application: you can use an already created bitmap or you can design your own. To use an existing bitmap, you can open it as a file. To support this, the Bitmap class provides the following constructor:

public:
    Bitmap(String ^ filename);

This constructor takes as argument the name of the file or the path to it. Here is an example of using it:

System::Void btnLoadPicture_Click(System::Object^  sender, 
				 System::EventArgs^  e)
{
    Bitmap ^ bmpOpen = gcnew Bitmap(L"woman.bmp");
}

Besides this constructor, Image, the parent of of the Bitmap class, provides the FromFile() method to its children. This method is overloaded with two versions. The first version uses the following syntax:

public:
    static Image^ FromFile(String^ filename);

As you can see, this is a static method that you call without instantiating the class. The method takes as argument the name of, or the path to, the file. It returns an Image object that you can then cast to a Bitmap. Here is an example:

System::Void Form1_Paint(System::Object^  sender,
			 System::Windows::Forms::PaintEventArgs^  e)
{
    Bitmap ^ bmpPicture =
		 static_cast<Bitmap ^>(Image::FromFile(L"professionals.png"));
}

Practical LearningPractical Learning: Getting a Picture

  1. Copy the following picture in the PictureView1 subfolder inside the PictureViewer1 folder of the current project
     
  2. Return to the form and double-click its body
  3. Implement the event as follows:
     
    System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e)
    {
        this->PictureIsLoaded = false;
        this->strPicture = L"horizon.jpg";
    }
  4. Save the form

Opening a Picture File

In your application, you may also want the user to be able to open a picture as file. To assist you with this, and as we learned in Lesson 9, you can use the Open File dialog box. As a reminder, to allow the user to open a picture in your application, add an OpenFileDialog control OpenFileDialog to your form or create one programmatically.

There are different types of graphic files with various extensions. The primary type of bitmap you will use in Microsoft Windows has the extension .bmp. There are many more graphic file extensions that Microsoft Windows supports. In our lessons, we cannot review all of them, their differences, advantages, or disadvantages. Simply know that most or all of the types of graphics you can think of are supported.

When providing an Open File dialog box to your application, if you will support various types of graphics, construct a filter accordingly. Here is an example from Microsoft Paint:

 

As you can see, the bitmap file is on top of the list.

Practical LearningPractical Learning: Opening a Picture

  1. In the Toolbox, click the OpenFileDialog button OpenFileDialog and click the form
  2. Using the Properties window, change the following characteristics:
    (Name): ofdPicture
    DefaultExt: bmp
    Filter: Bitmap Files (*.bmp)|*.bmp|JPEG Files (*.jpg,*.jpeg)|*.jpg|GIF Files (*.gif)|*.gif|PNG Files (*.png)|*.png
    Title: Open a Picture
  3. On the form, double-click the button and implement its event as follows:
     
    System::Void btnOpenPicture_Click(System::Object^  sender,
    				  System::EventArgs^  e)
    {
        if( this->ofdPicture->ShowDialog() == 
    	 System::Windows::Forms::DialogResult::OK )
        {
    	 this->strPicture = this->ofdPicture->FileName;
    	 this->PictureIsLoaded = false;
    	 Invalidate();
        }
    }
  4. Save the form

Designing a Bitmap

As opposed to opening an existing picture, you can create your own, using the various classes and accessories of the GDI+ library. You can design a picture inside of Microsoft Visual C++ studio or you can use an external application.

To create a bitmap in Microsoft Visual C++:

  • In the Solution Explorer, you can right-click Resource Files -> Add -> Resource...
  • You can first display the Resource View window. To do this, on the main menu, you can click View -> Other Windows -> Resource View. Then, in the Resource View, you can right-click the name of the project -> Add -> Resource

Any of these actions would display the Add Resource dialog box. In the Add Resource dialog box, click Bitmap:

Add Resource
 

And click New. A new file with an extension of .bmp would be added to the project script of your project. You can then design it as you see fit. Here is an example:

Instead of designing an image, you can also copy it from an external application and paste it in Bitmap window.

To create or design a bitmap externally, you can use any graphics application, including the Paint program that is installed with Microsoft Windows:

Creating a picture in Paint

There are many other more sophisticated applications used to create and manipulate graphics. As long as you can create an save a valid picture, you can use that picture in your application.

Presenting a Bitmap

Once the picture is ready, to present it to the user, for example to display it in your application, you can call the Graphics::DrawImage() method that is overloaded with as many different versions as you can possibly need. One of the versions of this method has the following syntax:

public:
    void DrawImage(Image ^ img, int x, int y);

The first argument can be a bitmap that you may have previously initialized. The second argument specifies the location where the picture will be drawn.

The Characteristics of a Bitmap

 

The Location of a Bitmap

To represent a picture in your application, such as on a form, the primary information you must provide is its location. The location of a picture is the measure, in pixels, of its top and its left corner with regards to the object that is hosting it:

Using the location, to specify where to display a picture, you can pass the x and y values as the second and the third arguments, respectively, of the Graphics::DrawImage() method. Here is an example:

System::Void btnDisplayPicture_Click(System::Object^  sender, 
				System::EventArgs^  e)
{
    Graphics ^ graph = CreateGraphics();
    Bitmap   ^ bmpPicture = gcnew Bitmap(L"woman.bmp");

    graph->DrawImage(bmpPicture, 40, 25);
}

As opposed to integers, you can also pass the location values as floating point numbers. This is done using the following version of the Graphics::DrawImage() method:

public:
    void DrawImage(Image^ image, float x, float y);

Here is an example:

System::Void Form1_Paint(System::Object^  sender,
			 System::Windows::Forms::PaintEventArgs^  e)
{
    Bitmap ^ bmpPicture =
		 static_cast<Bitmap ^>(Image::FromFile(L"professionals.png"));
    e->Graphics->DrawImage(bmpPicture, 10.50f, 12.20F);
}

You can also specify the location as a Point. If the properties of the Point are integers, you can use the following flavor of the Graphics::DrawImage() method:

public:
    void DrawImage(Image^ image, Point point);

If the values of the Point are floating point numbers, you can use the following version:

public:
    void DrawImage(Image^ image, PointF point);

Practical LearningPractical Learning: Positioning a Picture

  1. Click the body of the form
  2. In the Properties window, click the Events button and double-click Paint
  3. Implement the event as follows:
     
    System::Void Form1_Paint(System::Object^  sender,
    			 System::Windows::Forms::PaintEventArgs^  e)
    {
        if( strPicture != L"" )
        {
    	 Image ^ bmpPicture = Image::FromFile(this->strPicture);
             e->Graphics->DrawImage(bmpPicture, 10, 40);
    	 this->PictureIsLoaded = true;
        }
    }
  4. Execute the application
     
  5. Try opening a picture
  6. Close the form and return to your programming environment

The Size of a Picture

A picture usually appears as a geometric figure such as a rectangle:

A Picture

Through some manipulations, a picture can appear non-rectangular. Regardless of the perception, a picture is meant to fit a rectangular figure. As such, a picture has a size, represented by a width and a height, in pixels. The width of a picture is the distance from its left to its right borders. The height of a picture is the distance, in pixels, between its top and its bottom borders. The size of a picture can be illustrated as follows:

The Size of a Picture

When creating a Bitmap object, you can specify its primary size. To do this, you can use the following constructor:

public:
    Bitmap(int width, int height);

The width and the height arguments are as we illustrated them above. Here is an example of using this constructor:

System::Void btnCreateBitmap_Click(System::Object^  sender,
			 System::EventArgs^  e)
{
    Bitmap ^ bmpSample = gcnew Bitmap(450, 625);
}

If you have a picture, you can find out what its size is. To assist you with knowing the width of a picture, the Image class, the parent of the Bitmap class, provides the Width property, which is of type integer. In the same way, to give you the height of a picture, the Image class is equipped with a property named Height, which also is an int type. Here is an example of getting the dimensions of a picture:

System::Void btnLoadPicture_Click(System::Object^  sender, 
				System::EventArgs^  e)
{
    OpenFileDialog ^ dlgOpen = gcnew OpenFileDialog;

    if( dlgOpen->ShowDialog() == ::DialogResult::OK )
    {
	 String ^ strFilename = dlgOpen->FileName;
	 Bitmap ^ bmpPicture = gcnew Bitmap(strFilename);
	 Graphics ^ graph = CreateGraphics();

	 graph->DrawImage(bmpPicture, 120, 12);
	 int width = bmpPicture->Width;
	 int height = bmpPicture->Height;

	 txtWidth->Text  = width.ToString();
	 txtHeight->Text = height.ToString();
    }
}

The Size of a Picture

To get both the width and the height as one object, the Image class provides to its children, such as Bitmap, the Size property. As you may guess, the Size property is of type Size.

Besides the Width, the Height, and the Size properties, to get the size of a bitmap, you can access the PhysicalDimensions property of the Image class. This property is of type SizeF but its values depend on the type of picture.

The Transparency of a Bitmap

In the previous lesson, we saw that a graphic could be made of thousands to millions of colors. When you display a picture in your application, you can ask Microsoft Windows to "see through" one particular color. Seeing through is referred to as transparency. This is an operation regularly needed in graphics applications, the operating system is already equipped to select a default color it considers for transparency. In most cases, you can use that color. Otherwise, for your particular application, you can specify what color you want to use as "see through".

To support picture transparency, the Bitmap class is equipped with the MakeTransparent() method that is overloaded with two versions. The first version uses the following syntax:

public:
    void MakeTransparent();

When you call this method, it lets the operating system choose the color used for transparency. In most cases, the operating system selects white as the transparency color. Consequently, when you display the picture, wherever a white spot or area is shown on the picture, that area would disappear to show behind it. Here is an example:

Building
System::Void Form1_Paint(System::Object^  sender, 
		System::Windows::Forms::PaintEventArgs^  e)
{
	 Bitmap ^ bmpBuilding = gcnew Bitmap(L"building.bmp");
	 e->Graphics->DrawImage(bmpBuilding , 0, 0);
				 
	 Bitmap ^ bmpMonument = gcnew Bitmap(L"monument.bmp");
	 bmpMonument ->MakeTransparent();
	 e->Graphics->DrawImage(bmpMonument , 200, 260);
}

This would produce:

Instead of using the default transparency color of the operating system, you can specify your own color. To support this, the Bitmap class provides another version of the MakeTransparent() method. Its syntax is:

public:
    void MakeTransparent(Color transparentColor);

 With this method, instead of letting the operating system determine the transparency color, you pass your own as argument. Here is an example:

Flying Bird
System::Void Form1_Paint(System::Object^  sender,
			 System::Windows::Forms::PaintEventArgs^  e)
{
    Bitmap ^ bmpFlying = gcnew Bitmap(L"flying.bmp");
    e->Graphics->DrawImage(bmpFlying, 0, 0);
				 
    Bitmap ^ bmpGlobe = gcnew Bitmap(L"globe.bmp");
    bmpGlobe->MakeTransparent(Color::Black);
    e->Graphics->DrawImage(bmpGlobe, 20, 120);
}

This would produce:

Practical LearningPractical Learning: Using the Transparency of a Picture

  1. To create a new program, on the main menu, click File -> New -> Project...
  2. In the Templates list, click Windows Forms Application
  3. Set the Name to ImageFloater and click OK
  4. From the Components section of the Toolbox, click Timer and click the form
  5. While the timer is still selected under the form, in the Properties window, set its Enabled property to True and its Interval to 1000
  6. Copy the following pictures (click the left picture to open the real one in the browser) in the ImageFloater folder inside the ImageFloater folder
     
    House
  7. Under the form, double-click the time1 control and implement its event as follows:
     
    System::Void timer1_Tick(System::Object^  sender, 
    	 System::EventArgs^  e)
    {
        Bitmap ^ bmpArea = gcnew Bitmap(Width, Height);
        Graphics ^ graphArea = Graphics::FromImage(bmpArea);
    
        Bitmap ^ bmpDiamond = gcnew Bitmap(L"diamond.bmp");
        bmpDiamond->MakeTransparent();
    
        Bitmap ^ bmpHouse = gcnew Bitmap(L"house.bmp");
        graphArea->DrawImage(bmpHouse, 0, 0);
    				 
        Random ^ rnd = gcnew Random;
        int rndLeft = rnd->Next(bmpHouse->Width);
        int rndTop  = rnd->Next(bmpHouse->Height);
        graphArea->DrawImage(bmpDiamond, rndLeft, rndTop);
    
        Graphics ^ painter = Graphics::FromHwnd(Handle);
        painter->DrawImage(bmpArea, 0, 0);
    }
  8. Execute the application to see the result

The Color of a Pixel

 

Setting the Color of, or Painting, a Pixel

In our introduction to GDI+, we saw that the screen of a computer monitor uses a series of horizontal and vertical lines, the intersection of two perpendicular lines is a pixel. Each pixel holds one color. Of course, two adjacent pixels can hold the same color or each can hold a different color.

A bitmap is a series of colored adjacent pixels. Put another way, for a group of pixels to be considered a bitmap, these pixels must constitute a group. A bitmap is made by specifying the color of each pixel. This means that the pictures we have used so far were simply made of pixels and each pixel held an appropriate color.

If you decide to create or design a picture using the tool resources in Microsoft Visual C++ available from the Resource View (or the Solution Explorer), you would experiment, on a large scale the ability to specify the color of each individual pixel, using (a limited list of) colors:

 

Actually, when you have a bitmap, you can access any pixel of the picture and then you can either specify its color or get its current color.

To allow you to specify the color of a pixel, the Bitmap class provides a method named SetPixel and its syntax is:

public:
    void SetPixel(int x, int y,	Color color);

The x and y arguments represent the left and top values of the location of the pixel. The 3rd argument specifies the new color that the pixel will hold. Here is an example:

System::Void Form1_Paint(System::Object^  sender, 
	System::Windows::Forms::PaintEventArgs^  e)
{
    Bitmap ^ bgDrawingArea = gcnew Bitmap(Width, Height);
    e->Graphics->DrawImage(bg, 0, 0);

    for(int i = 0; i < Width; i += 20)
	for(int j = 0; j < Height; j += 20)
	{
	    bgDrawingArea->SetPixel(i, j, Color::White);
		 
	    Graphics ^ painter = Graphics::FromHwnd(Handle);
	    painter->DrawImage(bgDrawingArea, 0, 0);
	}
}

To know the color of a pixel on a picture, you can call the Bitmap::GetPixel() method whose syntax is:

public:
    Color GetPixel(int x, int y);

The x and y arguments represent the left and top values of the location of the pixel whose color you want to get. This method returns the color of that pixel. 

Getting the Color of a Pixel

We previously mentioned that a picture was a series of pixels with each pixel holding a color. As opposed to specifying the color of a pixel, you can retrieve its color. To support this, the Bitmap class is equipped with a method named GetPixel. Its syntax is:

public:
    Color GetPixel(int x, int y);

As you can see, this method takes two arguments that represent the Cartesian coordinates of the pixel. The method returns a Color value.

Practical LearningPractical Learning: Accessing the Color of a Pixel

  1. To create a new program, on the main menu, click File -> New -> Project...
  2. In the Templates list, click Windows Forms Application
  3. Set the Name to ColorSelector and click OK
  4. Copy the following picture and paste it somewhere in your computer
     
  5. Design the form as follows:
     
    Control Text Name Other Properties
    PictureBox   pbxColor Image: colorpal1.jpg
    Label Red:    
    TextBox   txtRed  
    Label Green:    
    TextBox   txtGreen  
    Label Blue:    
    TextBox   txtBlue  
    Panel   pnlPreview BorderStyle: FixedSingle
    Button Close btnClose  
  6. Right-click the form and click View Code
  7. In the body of the class, declare a Boolean variable named IsSelecting:
     
    private:
    		/// <summary>
    		/// Required designer variable.
    		/// </summary>
    		System::ComponentModel::Container ^components;
    		bool isSelecting;
  8. Return to the form and double-click an unoccupied area of its body
  9. Implement the event as follows:
     
    System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e)
    {
        isSelecting = false;
    }
  10. Return to the form and click the picture box control on it
  11. In the Properties window, click the Events button and double-click MouseDown
  12. Implement the event as follows:
     
    System::Void pbxColor_MouseDown(System::Object^  sender,
    			 System::Windows::Forms::MouseEventArgs^  e)
    {
        isSelecting = true;
    }
  13. Return to the form and click the picture box control on it
  14. In the Events section of the Properties window, double-click MouseUp and implement the event as follows:
     
    System::Void pbxColor_MouseUp(System::Object^  sender,
    			System::Windows::Forms::MouseEventArgs^  e)
    {
        isSelecting = false;
    }
  15. Return to the form and click the picture box control on it
  16. In the Events section of the Properties window, double-click MouseMove and implement the event as follows:
     
    System::Void pbxColor_MouseMove(System::Object^  sender,
    			 System::Windows::Forms::MouseEventArgs^  e)
    {
        if( isSelecting == true )
        {
    	 Bitmap ^ bmpImage = static_cast<Bitmap ^>(pbxColor->Image);
    	 Color clr = bmpImage->GetPixel(e->X, e->Y);
    
    	 txtRed->Text = clr.R.ToString();
    	 txtGreen->Text = clr.G.ToString();
    	 txtBlue->Text = clr.B.ToString();
    
    	 pnlPreview->BackColor = clr;
        }
    }
  17. Execute the application
  18. Click the mouse on the picture mouse and drag to produce a color
     
  19. Close the form
 
 

Previous Copyright © 2007, yevol.com Next