Home

Operations on Bitmaps

 

Scaling, Mirroring, Flipping, and Rotating a Picture

 

Scaling a Picture

Scaling a picture consists of changing its size, either to widen, to enlarge, to narrow, to heighten, or to shrink it. Although there are various complex algorithms you can use to perform this operation, the Bitmap class provides a shortcut you can use. Of course, in order to scale a picture, you must first have one.

To support picture scaling, the Bitmap class provides the following constructor:

public Bitmap(Image original, int width, int height);

The original argument is the Image, such as a Bitmap object, that you want to scale. The width and the height arguments represent the new size you want to apply to the picture. After this constructor has been used, you get a bitmap with the new size. Here is an example of using it:

Picture Normal Size

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ExoPicture1
{
    public partial class Form1 : Form
    {
        Bitmap bmpPicture;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            bmpPicture = new Bitmap(10, 10);
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawImage(bmpPicture, 120, 12);
        }

        private void btnLoadPicture_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlgOpen = new OpenFileDialog();

            if (dlgOpen.ShowDialog() == DialogResult.OK)
            {
                String strFilename = dlgOpen.FileName;
                bmpPicture = new Bitmap(strFilename);
                int width = bmpPicture.Width;
                int height = bmpPicture.Height;

                textBox1.Text = width.ToString();
                textBox2.Text = height.ToString();

                Invalidate();
            }
        }

        private void btnResize_Click(object sender, EventArgs e)
        {
            int width  = 0,
                height = 0;

            try
            {
                width = int.Parse(textBox1.Text);
            }
            catch (FormatException)
            {
                MessageBox.Show("The value you entered for the width is not valid");
            }

            try
            {
                height = int.Parse(textBox2.Text);
            }
            catch (FormatException)
            {
                MessageBox.Show("The value you entered for the height is not valid");
            }

            Bitmap bmpNew = new Bitmap(bmpPicture, width, height);
            bmpPicture = bmpNew;
            Invalidate();
        }
    }
}

Picture Resized

You can also specify both the width and the height as the size. To do this, you can use the following constructor:

public Bitmap(Image original, Size newSize);

As you can see, the scaling operation could produce a kind of distorted picture. An alternative would be to keep the ration of both dimensions while changing the value of one.

Mirroring a Picture

When it comes to bitmaps, mirroring is the process of changing the horizontal direction of a picture. For example imagine you have the picture of a person directed to the right:

With mirroring, you can make that face look to the left:

To support mirroring, the Bitmap class inherits a method named RotateFlip from its parent Image class. Its syntax is:

public void RotateFlip(RotateFlipType rotateFlipType);

This function takes one argument that specifies the mirroring option through the RotateFlipType enumeration. The members of  the RotateFlipType enumeration that can be used to mirror a picture are RotateNoneFlipX and Rotate180FlipY. Here is an example of mirroring a picture:

private void btnManipulate_Click(object sender, EventArgs e)
{
        Bitmap bmpPicture = new Bitmap("person.jpg");
        bmpPicture.RotateFlip(RotateFlipType.RotateNoneFlipX);
        CreateGraphics().DrawImage(bmpPicture, 10, 10);
}

When this method is called, the bitmap horizontal direction would be changed.

Flipping a Picture

Flipping a picture consists of changing its vertical direction. For example you may have a picture that seems to be oriented down:

Flip

By flipping, you can make the picture point up:

To support picture flipping, you can call the same RotateFlip() method of the Image class. This time, you would use a different value for the argument. The member of the RotateFlipType enumeration used to flip a picture is  RotateNoneFlipY. Here is an example of flipping a picture:

private void btnManipulate_Click(object sender, EventArgs e)
{
        Bitmap bmpPicture = new Bitmap("Pushpin.jpg");
        bmpPicture.RotateFlip(RotateFlipType.RotateNoneFlipY);
        CreateGraphics().DrawImage(bmpPicture, 10, 10);
}

Rotating a Picture

Rotating a picture consists of changing its angular orientation. The Image class supports this operation (with somewhat limited options) through its RotateFlip() method. As mentioned for mirroring and flipping, the value you pass as argument would determine how the operation is carried out.

The members of the RotateFlipType enumeration that are used to rotate a picture are:

  • RotateNoneFlipNone: Nothing would happen
  • Rotate90FlipNone: The picture is rotated at 90 clockwise. As a result, after calling the method with this member, what is on the left of the original picture would be positioned in the top section of the picture. Here is an example:
     
    Original After Calling the Method
    =>
    Notice that, after the method has been called, the person is still holding the remote control with his right hand. Here is an example:
    private void btnRotate_Click(object sender, EventArgs e)
    {
            Bitmap bmpPicture = new Bitmap("person1.gif");
            bmpPicture.RotateFlip(RotateFlipType.Rotate90FlipNone);
            CreateGraphics().DrawImage(bmpPicture, 10, 10);
    }
  • Rotate180FlipNone: The picture is rotated at 90 clockwise twice. This means that the picture is first rotated at 90, then rotated again at 90. As a result, after calling the method with this member, what is on the left of the original picture would be positioned in the right section but what is on the top would be positioned to the bottom of the picture. Here is an example:
     
    Original
    After Calling the Method
    Notice that, after the method has been called, the person is still holding the remote control with his right hand. As a result, the remote control is on opposite sites of the pictures, indicating that it is the same hand.
    You can get the same result by calling the method twice with the Rotate90FlipNone member each time:
    private void btnRotate_Click(object sender, EventArgs e)
    {
            Bitmap bmpPicture = new Bitmap("person1.gif");
            bmpPicture.RotateFlip(RotateFlipType.Rotate90FlipNone);
            bmpPicture.RotateFlip(RotateFlipType.Rotate90FlipNone);
            CreateGraphics().DrawImage(bmpPicture, 10, 10);
    }
  • Rotate270FlipNone: The picture is rotated at 90 clockwise three times. This means that the picture is first rotated at 90, then rotated again at 90, and then rotated again at 90. Here is an example:
     
    Original After Calling the Method
    =>
    Notice that, after the method has been called, the person is still holding the remote control with his right hand.
    You can get the same result by calling the method three times with the Rotate90FlipNone member each time:
    private void btnRotate_Click(object sender, EventArgs e)
    {
            Bitmap bmpPicture = new Bitmap("person1.gif");
            bmpPicture.RotateFlip(RotateFlipType.Rotate90FlipNone);
            bmpPicture.RotateFlip(RotateFlipType.Rotate90FlipNone);
            bmpPicture.RotateFlip(RotateFlipType.Rotate90FlipNone);
            CreateGraphics().DrawImage(bmpPicture, 10, 10);
    }
  • Rotate180FlipXY: No real change. Actually, the picture is rotated at 90 four times and then gets back to its original orientation and position:
     
    Original
    After Calling the Method
  • Rotate90FlipX: The picture is mirrored, then rotated at 90 counterclockwise (or rotated at 90 counterclockwise then mirrored):
     
    Original After Calling the Method
    =>
    Notice that, after the method has been called, the person is now holding the remote control with his left hand
  • Rotate180FlipX: The picture is mirrored, then rotated at 180 counterclockwise twice (or rotated at 180 counterclockwise twice then mirrored):
     
    Original
    After Calling the Method
    Notice that, after the method has been called, the person is now holding the remote control with his left hand. As a consequence, the remote control is on the same side of the screen on both pictures (compare with Rotate180FlipNone)
  • Rotate270FlipX: The picture is mirrored, then rotated at 90 counterclockwise three times (or rotated at 90 counterclockwise three times then mirrored):
     
    Original After Calling the Method
    =>
    Notice that, after the method has been called, the person is now holding the remote control with his left hand
  • Rotate90FlipY: Produces the same result as Rotate270FlipX 
  • Rotate270FlipY: Produces the same result as Rotate90FlipX
  • Rotate90FlipXY: Produces the same result as Rotate270FlipNone
  • Rotate270FlipXY: Produces the same result as Rotate90FlipNone
  • RotateNoneFlipXY: Produces the same result as Rotate180FlipNone

Introduction to the Picture Box

 

Description

As we have seen regularly in this and as you will see in other lessons, you can display a picture directly on a form. Still, to give you a more comfortable space to show a picture, the .NET Framework provides a Windows control named PicturePox.

Getting a Picture Box

Like most controls and as we described in our introduction to control design, to get a picture box, from the Toolbox, you can click the PictureBox PictureBox button and click the form. To programmatically get the control, you can create a handle to the PictureBox class. Before using the control, make sure you add it to the list of Controls of the form that will host it. Here is an example:

using System;
using System.Windows.Forms;

public class Exercise : Form
{
    private PictureBox pctBox;

    public Exercise()
    {
    }

    private void InitializeComponents()
    {
        pctBox = new PictureBox();
        Controls.Add(pctBox);
    }
}

public class Program
{
    public static int Main()
    {
        Application.Run(new Exercise());
        return 0;
    }
}

The Characteristics of a Picture Box

 

Introduction

As a regular visual control, after a picture box has been added to a form, it assumes a default size (unless you dragged and drew when adding it). You can then move or resize it using the techniques of application design we reviewed in Lessons 3 and 4. Of course, you can also specify the location and the size of the control programmatically. Here is an example:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Exercise : Form
{
    private PictureBox pctBox;

    public Exercise()
    {
        InitializeComponents();
    }

    private void InitializeComponents()
    {
        pctBox = new PictureBox();
        pctBox.Location = new Point(10, 10);
        pctBox.Size = new Size(200, 150);
        Controls.Add(pctBox);
    }
}

public class Program
{
    public static int Main()
    {
        Application.Run(new Exercise());
        return 0;
    }
}

The Border Style of a Picture Box

By default, when you have added a picture box to a form, it appears without borders. At run time, the form designer would show the borders so you can conveniently move or resize it:

Picture Box

At run time, unless you display an object in the picture box or draw a shape in it, the user would not know where the picture box starts and where it ends:

Picture Box

There is no way of knowing that the above form contains a picture box. If you want the picture box to show its borders to the user, you can use the BorderStyle property. We described this property in Lesson 5.

The Image of a Picture Box

As stated in the introduction, the primary purpose of a picture box is to display a picture. To support this, the PictureBox class is equipped with a property named Image. This property is of type Image. At design time, to specify the picture that this control would hold, first click the picture box on the form to select it:

  • Click the triangular button in the top line:
     

     
    and click Choose Image
  • Click the ellipsis button of the Image field in the Properties window

In both cases, a dialog box would come up to assist you with locating and selecting a picture. 

To programmatically specify the picture to display, assign an Image object to the instance of the PictureBox class. Here is an example:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Exercise : Form
{
    private PictureBox pctBox;

    public Exercise()
    {
        InitializeComponents();
    }

    private void InitializeComponents()
    {
        pctBox = new PictureBox();
        pctBox.Location = new Point(10, 10);
        pctBox.Size = new Size(200, 150);
        pctBox.Image = Image.FromFile(@"E:\Programs\Person.bmp");
        Controls.Add(pctBox);
    }
}

public class Program
{
    public static int Main()
    {
        Application.Run(new Exercise());
        return 0;
    }
}

If you decide to specify the picture programmatically, make sure you provide a valid picture or a valid path to the picture; otherwise you would receive an error if the application cannot find the image.

The Image Location of the Image of a Picture Box

Besides the PictureBox.Image property, to assist you with specifying the image to display, the PictureBox class provides a property named ImageLocation. This property, which is of type String, expects either the path to the file or the URL of the image. At design time, difference with the Image property is that you are not asked to selected a picture but to give its location. Therefore, to use it, in the Properties window, type the complete path:

Properties Window 

Remember that you can also provide a URL to the picture:

Properties Windows

In both cases, if you provide a bad path or a broken link, that is, if the compiler cannot find the image, the picture box would display an X icon on its body.

At run time, you can also specify the path or the URL to the picture by assigning it to the PictureBox.ImageLocation property. Here is an example:

public class Exercise : Form
{
    private PictureBox pctBox;

    public Exercise()
    {
        InitializeComponents();
    }

    private void InitializeComponents()
    {
        pctBox = new PictureBox();
        pctBox.Location = new Point(10, 10);
        pctBox.Size = new Size(200, 150);
        pctBox.ImageLocation = "http://www.functionx.com/cars/civic.gif";
        Controls.Add(pctBox);
    }
}

After assigning a string to the ImageLocation property, you can call the PictureBox.Load() method to actually show the image. This method is overloaded with two versions.

When accessing this property, if you use an event such as the Paint event of the picture box or the Click event of a button, you don't have to call the Load() method to show the picture; but it is more effective and faster.

Instead of assigning a string to the PictureBox.ImageLocation property and calling the parameter-less PictureBox.Load() method, you can call the other version of the method. Its syntax is:

public void Load(string url);

This version takes as argument the URL of, or the path to, the picture. Here is an example:

public class Exercise : Form
{
    private PictureBox pctBox;

    public Exercise()
    {
        InitializeComponents();
    }

    private void InitializeComponents()
    {
        pctBox = new PictureBox();
        pctBox.Location = new Point(10, 10);
        pctBox.Size = new Size(200, 150);
        pctBox.Load(@"E:\Programs\person.bmp");
        Controls.Add(pctBox);
    }
}

After you have specified the image that the picture box would display, by default, it is located from the top-left corner of the control. In some cases, for example if the picture's size is lower than the control's, this would be fine and you may not need to be concerned with that:

The picture box can show only as far as its size. If an image goes beyond the control, its parts would be hidden. In some cases, the image may appear too wide, too narrow, too tall, or too short for the picture box. And in some cases, if the image's size is higher than the picture box, the control would not show some important aspects. Therefore, in some cases, you want to resize either the picture to fit the control, or the control to fit the picture. In some cases, you can programmatically resize a control by changing its Size property. On the other hand, you can scale a picture as we learned with bitmap. The PictureBox class provides an alternative.

The Size Mode of a Picture Box

The SizeMode property of the PictureBox class allows you to specify how the image in the control would be displayed. This property is based on the PictureBoxSizeMode enumeration and its members are as follows:

  • Normal: The picture is positioned from the top-left corner of the control as seen in the above form
  • CenterImage: The picture is positioned in the middle-center of the control
     

     
    If you give the user the ability to resize the picture box, when this is done, the picture would always be drawn in the middle-center of the control
  • StretchImage: The picture is resized to fit the control. Any dimension of the picture that is lower than its equivalent on the control is increased to match its equivalent. Any dimension of the picture that is higher than its equivalent on the control is decreased to match its equivalent:
      
    Before After
     
    Before After

    If you give the user the ability to resize the picture box, when this is done, the picture would always resize itself to fit the size of the control
  • Zoom: The image is positioned in the middle of the control but it is also resized following a certain algorithm:
    • If the image is taller than the control, the picture gets resized to be smaller so its new width and height can fit in the control and the ratio Bitmap.Width/Bitmap.Height ratio is respected. Here is an example
       
      Before After
    • If the image is wider than the control, the picture gets resized to be small enough so its new width and height can fit in the control and the ratio Bitmap.Width/Bitmap.Height is respected. Here is an example
       
      Before After
    • Imagine the image is smaller than the control:
       


      In this case, the picture's width and height would be increased but the ratio Bitmap.Width/Bitmap.Height is kept.
      To resize the picture, the compiler first finds out what dimension is closer to its equivalent of the control:
      • If the PictureBox.Height/Bitmap.Height ratio is lower than the PictureBox.Width/Bitmap.Width ratio, then the height of the image would first be increased to match the height of the picture box. Then the compiler would use the Bitmap.Width/Bitmap.Height ratio to calculate and apply the new width of the picture. Here is an example:
         
        Before After
      • If the PictureBox.Width/Bitmap.Width ratio is lower than the PictureBox.Height/Bitmap.Height  ratio, then the width of the image would first be increased to match the width of the picture box. Then compiler would then use the Bitmap.Width/Bitmap.Height ratio to calculate and apply the new height of the picture. Here is an example:
         
        Before After

    If you give the user the ability to resize the picture box, every time this is done, the compiler would use the above descriptions to resize and position the picture inside of the control

  • AutoSize: The size of the control would be changed to fit the picture:
    • If the picture is smaller than the control, the size of the control would be increased to show the whole picture
       
      Before After
    • If the picture is bigger than the control, the size of the picture box control would be decreased to fit the picture
       
      Before After
    If you had given the user the ability to resize the picture box, it cannot be resized and the size of the picture cannot change
 
 

Previous Copyright 2008-2009, yevol.com Next