Title: Resize images in C#
You can use MS Paint to easily resize images. Unfortunately, it won't preserve transparency if you save the result. I often need to resize transparent images so I finally got around to writing this example. It lets you resize images and save the result while preserving transparency.
This example is relatively simple. It lets you load and resize an image and then save the result. You specify the scale factor as a fraction. You cannot indicate the desired size of the new image. It does show you the new size, however, so you can just tweak the scale factor until you get the size you want. It also always sizes the image proportionally so you can't distort the result.
The key to the program is the following ShowResult method, which resizes the image and displays the result.
// Make and show the resized image.
private void ShowResult()
{
lblSize.Text = "Size:";
picResult.Visible = false;
if (OriginalImage == null) return;
// Get the scale.
float scale;
if (!float.TryParse(txtScale.Text, out scale))
return;
if (scale < 0.0001) return;
int width = (int)(OriginalImage.Width * scale);
int height = (int)(OriginalImage.Height * scale);
lblSize.Text = string.Format("Size: {0} x {1}",
width, height);
// Make the resized image.
Bitmap bm = new Bitmap(width, height);
using (Graphics gr = Graphics.FromImage(bm))
{
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle dest_rect = new Rectangle(0, 0,
width, height);
Rectangle source_rect = new Rectangle(0, 0,
OriginalImage.Width, OriginalImage.Height);
gr.DrawImage(OriginalImage,
dest_rect, source_rect, GraphicsUnit.Pixel);
}
picResult.Image = bm;
picResult.Visible = true;
}
The method first resets the lblSize label and sets the picResult PictureBox control's image to null.
Next, the code tries to parse the text in the txtScale text box to see what scale factor you want to use. The method uses the scale factor to calculate the new image size and displays its dimensions in the lblSize label.
The method then makes a new Bitmap with the desired size and creates an associated Graphics object. It sets the Graphics object's InterpolationMode property so the object will resize images smoothly.
The code creates rectangles representing the original and new bitmaps' areas. I then uses the Graphics object's DrawImage method to copy the original image onto the new Bitmap.
Finally, the code displays the resized image in the picResult PictureBox and makes that control visible.
The example program only contains a few other pieces of code, which help it load and save image files. Download the example to see those details.
Download the example to experiment with it and to see additional details.
|