Page 1 of 1

Compress Image With C# & System.Drawing.Imaging

#1 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1619
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Posted 30 December 2009 - 12:14 AM

Recently in the C# forum someone was asking how they would compress an image from ASP.NET, and I found this to be an interesting (and intriguing topic). So much so that I spent some time playing (and researching) to see what kind of solution I could come up with, so let's talk about that:

First you must have at least a working knowledge of the System.Drawing Namespace in the Framework. Here you will be introduced to some members that (maybe) you haven't had to deal with before, and once we are done you should at least have a better understanding of how they work, and what they do. First thing we will look at will be the ImageCodecInfo Class, this gives us the ability to retrieve the proper codec for the specified mime type.

With this we will create a method that returns an ImageCodecInfo object for whatever image we're working with. Here is how this method will look (odd namely named GetEncoderInfo and expects a string paramneter that is the mime type we're working with. Here's this method:

/// <summary>
/// method for getting the right codec for the specified mime type
/// </summary>
/// <param name="mimeType">mime type we're looking for</param>
/// <returns></returns>
private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
	//create an array of ImageCodecInfo by using GetImageEncoders()
	ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();

	//first loop through all the encoders that were returned from our ImageCodecInfo array
	for (int i = 0; i < encoders.Length; ++i)
		//now we need to check for a match to the mime type we're providing
		//otherwise we return null
		if (encoders[i].MimeType.ToLower() == mimeType.ToLower())
			return encoders[i];

	return null;
}



That was easy, hey you over there, you can get out from under your desk it really wasn't that scary. Now we get top move onto doing the actual compressing and saving the image. Before we look at any code we'll be taking a look at the classes we'll be introduced to in this example. We need to research the EncoderParameters Class, this class encapsulates an array of EncoderParameter Objects. The EncoderParameter class is used to pass a value, even an array of values, to an image encoder.

So here is the method that does the actual saving of the image with the specified compression value (It's kind of neat if you ask me, if you work with graphics Namespace this will be yet another feather to put into your cap:

/// <summary>
/// method for saving the image with the proper quality & compression value
/// </summary>
/// <param name="img">image we're saving</param>
/// <param name="file">name we want to save the image as</param>
/// <param name="compressionValue">how much do we want to compress it</param>
private void ApplyCompressionAndSave(Image img, string file, long compressionValue, string mimeType)
{
	try
	{
		//create our EncoderParameters object and pass the values to the EncoderParameter class
		EncoderParameters parameters = new EncoderParameters(1);
		parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, compressionValue);
		ImageCodecInfo codec = GetEncoderInfo(mimeType);

		//now verify that the encoder returned from GetEncoderInfo isnt a null value
		if (codec != null)
			//an encoder was found so now we can save the image with the specified compression value
			img.Save(file, codec, parameters);
		else
			//no encoder was found so throw an exception
			throw new Exception("Codec information not found for the mime type specified. Check your values and try again");
	}
	catch (Exception ex)
	{
		MessageBox.Show(ex.Message);
	}   
}



Ok, all those of you huddling in the corner can come out now, we didn't blow anything up and all is safe, honestly. We were able to take an image and save the image in a compressed format while attempting to keep the quality level as high possible throughout the process.

Thanks for reading, and all the best to you in your programming lives :)

Is This A Good Question/Topic? 1
  • +

Replies To: Compress Image With C# & System.Drawing.Imaging

#2 FlashM  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 380
  • View blog
  • Posts: 1,195
  • Joined: 03-December 09

Posted 30 December 2009 - 01:36 AM

Great tutorial!
The only thing I'm missing is some example of methods input parameters and an explanation what is the mimeType, what can be the mimeType arguments and what is the MIN and MAX value for compressionValue. But otherwise, really nice and interesting tut. Thanks!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1