Visual C#

Operations on Bitmaps: Mirroring a Picture

Mirroring a picture consists of changing the horizontal direction of a picture. This is done by transferring each pixel from the source of the picture to…

1 min read158 words3 code samples

Introduction#

Mirroring an image means reversing its horizontal alignment. This is achieved by mapping each pixel from the original location to a corresponding spot on the opposite side of the target image:

To mirror a picture, get each of its pixels from one side of its horizontal position and transfer it to the opposite side of the horizon position. The vertical position of each pixel stays the same. This can be done as follows:

C#
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 Mirror
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnMirror_Click(object sender, EventArgs e)
        {
            Graphics graph = pbxSource.CreateGraphics();
            Bitmap bmpSource = (Bitmap)pbxSource.Image;
            Bitmap bmpDestination =
                new Bitmap(pbxDestination.ClientSize.Width,
                           pbxDestination.ClientSize.Height);

            int width = bmpSource.Width;
            int height = bmpSource.Height;

            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    Color clr = bmpSource.GetPixel(x, y);
                    bmpDestination.SetPixel(width - x - 1, y, clr);
                }
            }

            pbxDestination.Image = bmpDestination;
        }
    }
}

Instead of writing custom logic, you can use the RotateFlip method inherited from the Image class by the Bitmap class. Its signature is as follows:

C#
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:

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

After executing this method, the horizontal orientation of the bitmap will be reversed. Home Copyright © 2010-2011 C# Key