Title: Resize pictures in a directory to specific widths or heights in C#
The post Resize pictures in a directory in C# lets you resize all of the pictures in a directory but it only scales the images. This example lets you resize pictures so they have a given width, height, or both. If you specify only one of the width or height, the program calculates the other value so the image is not distorted.
ResizeBitmap
After some preliminaries, the program loops through the files in the selected directory and calls the following ResizeBitmap method for each.
// Resize a bitmap to the given dimensions.
// If one dimension is omitted, scale the image uniformly.
private Bitmap ResizeBitmap(Bitmap bm,
bool set_width, bool set_height,
int new_width, int new_height)
{
Rectangle from_rect =
new Rectangle(0, 0, bm.Width, bm.Height);
// Calculate the image's new width and height.
int wid2, hgt2;
if (set_width)
wid2 = new_width;
else
wid2 = bm.Width * new_height / bm.Height;
if (set_height)
hgt2 = new_height;
else
hgt2 = bm.Height * new_width / bm.Width;
// Make the new image.
Bitmap bm2 = new Bitmap(wid2, hgt2);
// Draw the original image onto the new bitmap.
Rectangle dest_rect = new Rectangle(0, 0, wid2, hgt2);
using (Graphics gr = Graphics.FromImage(bm2))
{
gr.InterpolationMode =
InterpolationMode.HighQualityBicubic;
gr.DrawImage(bm, dest_rect, from_rect,
GraphicsUnit.Pixel);
}
return bm2;
}
This method first creates a rectangle representing the area that will be copied. That includes the entire input image.
It then calculates the new image's width and height. If the set_width parameter is true, the program sets the new width equal to the value in parameter new_width. If set_width is not true, the code calculates a new width that uses the same scale needed to map the original height to the new height.
The method then repeats the same steps to calculate the new image's height.
Note that this code scales one dimension if it is not specified. If both dimensions are specified, then it uses both of them for the new image.
Having calculated the new image's dimensions, the code creates the new Bitmap and makes an associated Graphics object. It then uses that object's DrawImage method to copy the original bitmap into the new one.
The method finishes by returning the new bitmap. The main program then saves the new Bitmap in a file with the same name as the original file with "_s" added at the end before the file extension.
Conclusion
This example loops through the graphic files in a directory and resizes them all. The ResizeBitmap method could be useful in other programs, too. For example, you might like to resize a single image so it has a particular width. That makes the ResizeBitmap method a useful addition to your programming toolkit.
Download the example to experiment with it and to see additional details.
|