Resize pictures in a directory in C#

example

This example shows how to resize pictures in a directory.

This program lets you enter a directory name and a scale factor. It then loads all of the bmp, gif, jpg, jpeg, and png files in that directory, resizes them, and saves the resized versions back into the directory with an “_s” added to their names. (I wrote this program to make smaller versions of a bunch of pictures I had taken, so the “_s” stands for “small.”)

The most interesting work occurs in the following event handler when you click the Go button.

// Process the files in the selected directory.
private void btnGo_Click(object sender, EventArgs e)
{
    float scale = float.Parse(txtScale.Text);
    if (scale == 0)
    {
        MessageBox.Show("Scale must not be zero.",
            "Invalid Scale", MessageBoxButtons.OK,
            MessageBoxIcon.Error);
        return;
    }
    Cursor = Cursors.WaitCursor;
    Refresh();

    DirectoryInfo dir_info = new DirectoryInfo(txtDirectory.Text);
    foreach (FileInfo file_info in dir_info.GetFiles())
    {
        try
        {
            string ext = file_info.Extension.ToLower();
            if ((ext == ".bmp") || (ext == ".gif") ||
                (ext == ".jpg") || (ext == ".jpeg") ||
                (ext == ".png"))
            {
                using (Bitmap bm = new Bitmap(file_info.FullName))
                {
                    picWorking.Image = bm;
                    Text = "howto_2005_resize_pics - " +
                        file_info.Name;
                    Application.DoEvents();

                    Rectangle from_rect =
                        new Rectangle(0, 0, bm.Width, bm.Height);

                    int wid2 = (int)Math.Round(scale * bm.Width);
                    int hgt2 = (int)Math.Round(scale * bm.Height);
                    using (Bitmap bm2 = new Bitmap(wid2, hgt2))
                    {
                        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);
                        }

                        string new_name = file_info.FullName;
                        new_name = new_name.Substring(0,
                            new_name.Length - ext.Length);
                        new_name += "_s" + ext;
                        SaveImage(bm2, new_name);

                        picWorking.Image = null;
                    }
                }
            } // if it's a graphic extension
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error processing file '" +
                file_info.Name + "'\n" + ex.Message,
                "Error",
                MessageBoxButtons.OK,
                MessageBoxIcon.Error);
        }
    } // foreach file_info

    Text = "howto_resize_pics";
    Cursor = Cursors.Default;
}

The code first gets the scale factor and displays the wait cursor. It then gets a DirectoryInfo object for the directory you entered in the text box and uses it to loop through the directory’s files. If a file’s extension is .bmp, .gif, .jpg, .jpeg, or .png (you can add others if you like), it processes that file.

The code loads the file into a Bitmap. It displays the bitmap and its name so you can see what it is doing. The images may go too fast to really see but at least you can tell something’s happening.

The program makes a Rectangle covering the original bitmap. It then creates a new scaled Bitmap and makes a Rectangle to fit it.

Next the code creates a Graphics object associated with the new Bitmap. It sets the Graphics object’s InterpolationMode property to HighQualityBicubic so the image is resized smoothly. The code draws the original image onto the new Graphics object, using the original Bitmap and the Rectangles to resize the image.

Finally the program composes a new file name and saves the file in an appropriate format. (See the example Save images with an appropriate format depending on the file name’s extension in C# for information about the SaveImage method.)


Download Example




This entry was posted in files, graphics and tagged , , , , , , , , , , , , , , , . Bookmark the permalink.

One Response to Resize pictures in a directory in C#

  1. Ello says:

    Another way to get _s into the name or change it to any value you want

    //Get index of period and insert _s there.
    string newName = file.Insert(file.IndexOf('.'), "_s");  
    
    public string NameOfNewFiles(string input)
    {
            return file.Insert(file.IndexOf('.'), input);           
    }

Leave a Reply

Your email address will not be published. Required fields are marked *