Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

Reducing JPEG Picture Quality using C#

Learn how to create an application that reduces the quality of JPEG pictures from a folder and then puts the new pictures into another folder.

On Sunday, October 7th 2007 at 01:30 AM
By Andrew Pociu (View Profile)
*****   (Rated 4.4 with 16 votes)
Contextual Ads
More C# Resources
Advertisement
Download this Visual Studio 2005 project Download this project (Visual Studio 2005)

Changing the picture quality of a JPEG file

In this C# programming tutorial we're going to create a quite useful little application - one that takes every JPEG picture in a folder and changes its quality to a desired rate, which obviously reduces the size of the JPEG file. Thus, aside from using an encoder to reduce the quality of the picture, you'll also learn how to scan a folder for files of a certain type, and put them in a ListBox.


Designing the application

Fire up Visual Studio 2005 and start a new C# Windows Application. On it draw two buttons - btnOpen and btnReduce - they will be used to select the folder where you want to look for the pictures to be modified, and the folder where the modified pictures will be stored. The big control on this page is the ListBox control named lstPhotos, it is where the list of files to be reduced in quality will be stored. Then there's numQual - a NumericUpDown with values of 1 to 100 - which will define the quality to which we want the pictures reduced. Finally the last control to add to the form is prgReduce - a ProgressBar that keeps track of the progress made in resizing all the files. You will see that the progress bar works quite fine, even though we're not going to use a separate thread for the picture reducing code.

Picture Quality Form

Remember when I said we added our last component to the form? I lied. We still need the two dialogs that fire up when the btnOpen and btnReduce are clicked. They allow the user to select the folder where they want the files to be picked up from, and where the new ones are to be dropped. These two are FolderBrowserDialogs and are named as follows:

FolderBrowserDialog


The code behind the application

Since we're going to be working with graphic files and directories, the following two using statements are appropriate:


using System.IO;

using System.Drawing.Imaging;



Our code is divided into two: the scanning of the folder from where we pick up the pictures, and the quality reducing and file saving code. The first part happens inside the click event of btnOpen:


private void btnOpen_Click(object sender, EventArgs e)

{

    if (fbdOpen.ShowDialog() == DialogResult.OK)

    {

        // Clear any previous items in the list

        lstPhotos.Items.Clear();

        // Run a loop through all the files in the directory at the selected path

        foreach(string Filename in Directory.GetFiles(fbdOpen.SelectedPath))

        {

            // We'll create a new FileInfo object from the file path

            FileInfo fiPicture = new FileInfo(Filename);

            // If it's a JPEG file

            if (fiPicture.Extension.ToLower() == ".jpeg" || fiPicture.Extension.ToLower() == ".jpg")

            {

                // Add it to the list of files

                lstPhotos.Items.Add(Filename);

            }

        }

    }

    // We want the ProgressBar to have the same maximum value as the number of pictures to resize

    prgReduce.Maximum = lstPhotos.Items.Count;

}



Being commented, the code should be pretty easy to figure out. All we do is loop through the files in the directory and if they have the jpeg/jpg extension, we add them to the list.
So let's move on to the click event of btnReduce, where the second and final piece of code exists, which is more interesting since its the actual code that reduces the quality:


private void btnReduce_Click(object sender, EventArgs e)

{

    // Reset the progress bar

    prgReduce.Value = 0;

    // Show the FolderBrowserDialog where the user selects where to save the files

    if (fbdSave.ShowDialog() == DialogResult.OK)

    {

        // We will store the correct image codec in this object

        ImageCodecInfo iciJpegCodec = null;

        // This will specify the image quality to the encoder

        EncoderParameter epQuality = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (int)numQual.Value);

        // Get all image codecs that are available

        ImageCodecInfo[] iciCodecs = ImageCodecInfo.GetImageEncoders();

        // Store the quality parameter in the list of encoder parameters

        EncoderParameters epParameters = new EncoderParameters(1);

        epParameters.Param[0] = epQuality;

 

        // Loop through all the image codecs

        for (int i = 0; i < iciCodecs.Length; i++)

        {

            // Until the one that we are interested in is found, which is image/jpeg

            if (iciCodecs[i].MimeType == "image/jpeg")

            {

                iciJpegCodec = iciCodecs[i];

                break;

            }

        }

 

        // Loop through the files in the list

        foreach (string strFile in lstPhotos.Items)

        {

            // Take another step on the progress bar

            prgReduce.PerformStep();

 

            // Create a new Image object from the current file

            Image newImage = Image.FromFile(strFile);

 

            // Get the file information again, this time we want to find out the extension

            FileInfo fiPicture = new FileInfo(strFile);

            // Save the new file at the selected path with the specified encoder parameters, and reuse the same file name

            newImage.Save(fbdSave.SelectedPath + "\\" + fiPicture.Name, iciJpegCodec, epParameters);

        }

    }

    // Open the folder containing the new items

    System.Diagnostics.Process.Start(fbdSave.SelectedPath.ToString());

}



What this code does is to retrieve the correct image codec for JPEG files; we will need it in order to change the quality of the file. The code can be improved nicely if put into its separate class and into its separate thread. It would also help the progress bar act more smoothly.

Compile the application and run. You just built yourself a little JPEG processing application:

Picture Quality Application
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by }{ombr3 on Monday, October 8th 2007 at 07:01 AM

Very good!

This helps a lot if you have much photos and want to upload them!
I will _NEVER_ again use MS Paint to edit each separate photo ^^

by jagadeesh on Friday, February 15th 2008 at 08:14 AM

excellant

by Max on Friday, April 25th 2008 at 12:39 PM

Very nice

by Jan le Roux on Saturday, August 23rd 2008 at 06:43 PM

Great stuff! Thanks!

by surendra on Wednesday, September 17th 2008 at 07:17 AM

thank you very much

by Prakhar Prakash on Friday, November 14th 2008 at 09:38 AM

Hi !

Excellent application. One thing-

do add

newImage.Dispose();

right after this line -

newImage.Save(fbdSave.SelectedPath "\\" fiPicture.Name, iciJpegCodec, epParameters);

Otherwise, the application becomes a resource hog as all opened images remain in memory

by Robert Werner on Sunday, February 22nd 2009 at 11:46 PM

Thank you for this. Very useful!

One thing though: I kept on getting a parameter error with the Image Save method. I did a bit of research on the MSDN site and they showed the parameter cast as a Long integer. Once I did that then all worked fine.

by shuhang on Friday, April 24th 2009 at 09:27 PM

The image's colordepth is 8b,but to use your software, the colordepth is becoming 24b,why?

by Vsaratkar on Thursday, October 15th 2009 at 09:33 AM

Very useful!!!

by ibar shah on Monday, December 7th 2009 at 05:02 AM

Excellent work, it help alot
Thanks

by Madushan on Monday, May 24th 2010 at 06:33 PM

Thx for the post..

by Ashu on Thursday, June 24th 2010 at 02:53 AM

Hi,

Can u tel me how to convert .CMP file in to the .jpg or .png or any other image format file...

Thanks in advance........

by Reza on Wednesday, July 21st 2010 at 04:51 AM

Thx you for this Veryyyyyyyyy useful..

by Reza on Wednesday, July 21st 2010 at 04:51 AM

Thx you for this Veryyyyyyyyy useful..

by Hardik on Thursday, December 16th 2010 at 04:51 AM

Good article. Thanks for help.

by Rajaprabhu on Sunday, February 6th 2011 at 05:04 AM

Whether the quality gets increased or only the size increases... plz rply..

by Rajaprabhu on Sunday, February 6th 2011 at 05:04 AM

Whether the quality gets increased or only the size increases... plz rply..

by balaji on Thursday, February 17th 2011 at 10:47 AM

hi,its working but the minimum quality can be set is 1, i need to reduce the quality to very very low (i.e -100) inorder to use in a application. tell me how to do this, thanks in advance

by hatef on Saturday, March 5th 2011 at 03:49 AM

hi
how to get jpeg quality of a image?
can get it?


thanks

by hatef on Saturday, March 5th 2011 at 03:49 AM

hi
how to get jpeg quality of a image?
can get it?


thanks

by GenF20 Plus on Monday, December 19th 2011 at 05:26 PM

This is a great trick and I didn’t know you can use C# to obtain the info of your computer

by Human Growth Hormone on Monday, December 19th 2011 at 05:28 PM

This is a great trick and I didn’t know you can use C# to obtain the info of your computer

by Phen375 on Monday, December 19th 2011 at 05:33 PM

Does this trick work for Mac too?

by GenFX on Monday, December 19th 2011 at 05:36 PM

Does this trick work for Mac too?

by Teeth Whitening Reviews on Monday, December 19th 2011 at 05:41 PM

I needed to create you this tiny word so as to give thanks once again for your pleasant techniques you have provided on this site. This has been shockingly open-handed with people like you to supply openly what exactly a number of people would've offered for an e book to help make some profit for themselves, precisely now that you could possibly have done it in case you desired.

by Nuratrim on Monday, December 19th 2011 at 05:43 PM

I needed to create you this tiny word so as to give thanks once again for your pleasant techniques you have provided on this site. This has been shockingly open-handed with people like you to supply openly what exactly a number of people would've offered for an e book to help make some profit for themselves, precisely now that you could possibly have done it in case you desired.

by Ultimate Maqui Berry on Monday, December 19th 2011 at 05:46 PM

Those concepts additionally worked as a good way to recognize that other people have the same desire really like my own to see significantly more in regard to this issue. Certainly there are numerous more pleasurable opportunities up front for people who looked over your blog.

by Best Diet Pills on Monday, December 19th 2011 at 05:48 PM

Those concepts additionally worked as a good way to recognize that other people have the same desire really like my own to see significantly more in regard to this issue. Certainly there are numerous more pleasurable opportunities up front for people who looked over your blog.

by Dental White on Monday, December 19th 2011 at 05:51 PM

I have to express my thanks to the writer just for rescuing me from such a difficulty. Because of browsing through the online world and seeing views which were not helpful, I believed my life was done. Existing without the presence of solutions to the problems you've fixed as a result of your main write-up is a crucial case, and the kind which could have in a wrong way affected my entire career if I hadn't discovered your website.

by Pure Acai Berry Max on Monday, December 19th 2011 at 05:52 PM

I have to express my thanks to the writer just for rescuing me from such a difficulty. Because of browsing through the online world and seeing views which were not helpful, I believed my life was done. Existing without the presence of solutions to the problems you've fixed as a result of your main write-up is a crucial case, and the kind which could have in a wrong way affected my entire career if I hadn't discovered your website.

by gd poker on Sunday, January 22nd 2012 at 03:28 PM

Hello. magnificent job. I did not anticipate this. This is a great story. Thanks!

by on Tuesday, January 24th 2012 at 05:46 AM

Once you have recreated the problem and captured these steps, you can save them to a file and send it to your support person, who can then open it up and view

by Burn on Tuesday, August 7th 2012 at 02:54 AM

Thank you, thank you :). Great job.


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Ads

From the creators of Geekpedia, a revolutionary new coupon website!

BargainEZ has coupons codes, printable coupons, bargains and it is the leading source of Passbook coupons for iPhone and iPod touch devices.

Coupons
Discover Geekpedia
Other Resources