Image Compressor Using Windows Forms With C#

Introduction

Here, I have used a Windows. Forms application to demonstrate how to reduce the size of an image by reducing the quality.

In this example, first, let's create a Windows Forms Project Template from the "Project Templates" section, as shown below.

Go to File -> New -> Project and follow the screen below.

new file

Next, design the form with two textboxes for reading the source path and destination path. Add three buttons – two buttons to browse the source and destination folders, respectively, and one button to compress the images. Add one Combobox to load some compress values. The design can be seen below.

Image Compressor  With C#

After designing, you need to load the Compress Quality combo box data; for that, write the following code in the Form load event.

private void Form1_Load(object sender, EventArgs e)
{
    for (int i = 10; i <= 100; i = i + 10)
    {
        cmbQuality.Items.Add(i);
    }
    cmbQuality.SelectedIndex = 4;
}

Next, let’s write the Browse functionality for both source and destination folders. The code for the Browse control is shown below.

Let’s create a common function that can load source or destination textboxes according to the browse button clicks and call that form "Search" buttons.

private void OpenFolderDialog(TextBox Filepath)
{
    FolderBrowserDialog folderDlg = new FolderBrowserDialog();
    folderDlg.ShowNewFolderButton = true;
    DialogResult result = folderDlg.ShowDialog();
    if (result == DialogResult.OK)
    {
        Filepath.Text = folderDlg.SelectedPath;
        Environment.SpecialFolder root = folderDlg.RootFolder;
    }
}
private void btnSouceBrowse_Click(object sender, EventArgs e)
{
    OpenFolderDialog(txtSource);
}
private void btnDestFolder_Click(object sender, EventArgs e)
{
    OpenFolderDialog(txtDestination);
}

Now, let’s write a function to compress the image.

using System.Drawing;
using System.Drawing.Imaging;
public static void CompressImage(string SoucePath, string DestPath, int quality)
{
    var FileName = Path.GetFileName(SoucePath);
    DestPath = DestPath + "\\" + FileName;
    using (Bitmap bmp1 = new Bitmap(SoucePath))
    {
        ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
        System.Drawing.Imaging.Encoder QualityEncoder = System.Drawing.Imaging.Encoder.Quality;
        EncoderParameters myEncoderParameters = new EncoderParameters(1);
        EncoderParameter myEncoderParameter = new EncoderParameter(QualityEncoder, quality);
        myEncoderParameters.Param[0] = myEncoderParameter;
        bmp1.Save(DestPath, jpgEncoder, myEncoderParameters);
    }
}
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
    foreach (ImageCodecInfo codec in codecs)
    {
        if (codec.FormatID == format.Guid)
        {
            return codec;
        }
    }
    return null;
}

In the above function, CompressImage, I am passing the source path, destination path, and quality number. Then, I am taking only the filename with extension from the source path and concatenating that with the destination path. After that, I read and modified the source file into the destination path using Bitmap.

First, create an ImageCodecInfo passing jpeg image format, create a quality encoder (QualityEncoder), and create one encoder parameter. Then, pass the quality encoder(QualityEncoder) which we have created already.

Here, pass the parameter value as Quality no., which is passed to this function. After creating the parameter, save the bitmap image by passing the destination path,

imageCodacInfo (jpgEncoder), and Encoder parameter.

Now, we can use our CompressImage function to compress the images by passing the source image path.

So, let’s add the functionality for the Compress button, as shown below.

private void btnCompress_Click(object sender, EventArgs e)
{
    string[] files = Directory.GetFiles(txtSource.Text);
    foreach (var file in files)
    {
        string ext = Path.GetExtension(file).ToUpper();
        if (ext == ".PNG" || ext == ".JPG")
        {
            CompressImage(file, txtDestination.Text, (int)cmbQuality.SelectedItem);
        }
    }
    MessageBox.Show("Compressed Images have been stored to\n" + txtDestination.Text);
    txtDestination.Text = "";
    txtSource.Text = "";
}

In this click event, first, collect all the file paths from the Source folder path using the Directory.GetFiles method and store to string array. Then, loop all the files and check the extensions if they are matched. Then, call the CompressImage function by passing the file path, destination folder path, and image quality from Combo Box.

Now, you can see the below output of source files and destination files with their respective sizes.

source file respectivefiles


Similar Articles