Operations on Bitmaps: 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…
Introduction#
Image scaling refers to altering the dimensions of a picture to make it wider, taller, larger, or smaller. While many sophisticated algorithms exist for this, the Bitmap class offers a convenient shortcut. Naturally, you must have an existing image to scale it. The following constructor is used for this purpose:
public Bitmap(Image original, int width, int height);The original parameter refers to the Image, such as a Bitmap, that you intend to resize. The width and height parameters define the new dimensions to be applied. Once this constructor is called, you receive a new bitmap of the specified size. Here is an example:
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();
}
}
}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);Scaling operations can sometimes result in a warped or distorted appearance. To prevent this, you might choose to maintain the aspect ratio while adjusting only one dimension. Home Copyright © 2010-2011 C# Key

