Home Search Contact us About us
Title Saving an Image in JPEG format
Summary A simple method that saves an Image type object as a JPEG image with the desired compression ration.
Contributor John McTainsh
Published 5-May-2002
Last updated 8-May-2002
Page rating   78% for 13 votes Useless Brilliant

Introduction

Just a quick note on how to save images in JPEG format. It can simply be modified to save any any other format your computer supports

How it works

Probably the simplest bay to load an graphic is to call something like;

Bitmap bmp = new Bitmap( "MyNicePicture.bmp" );

Because the Bitmap Inherits from the Image class we can pass it into the following method to save it at any compression level we please. Note, the method actually searches for the matching Codec to perform the save operation. By changing the MimeType we look for we can save in different formats. Be sure to check if the Codec exist as they vary depending on operating system and installed application.

/// <summary>
/// Save the image using the given format
/// </summary>
/// <param name="sFileName">Full name of file to save as</param>
/// <param name="img">image to save</param>
/// <param name="nQuality">quality to save as, if applicable</param>
/// <returns>true if all went well</returns>
private bool SaveJpeg( string sFileName, Image img, long nQuality )
{
    try
    {
        // Build image encoder details
        ImageCodecInfo  [] encoders = ImageCodecInfo.GetImageEncoders();
        EncoderParameters  encoderParameters = new EncoderParameters( 1 );
        encoderParameters.Param[0] = new EncoderParameter( Encoder.Quality, nQuality );

        // Get jpg format ID
        foreach( ImageCodecInfo encoder in encoders )
        {
            if( encoder.MimeType == "image/jpeg" )
            {
                // Save
                img.Save( sFileName, encoder, encoderParameters );
                return true;
            }
        }
        Console.WriteLine( "Suitable JPEG encoder format not found" );
    }
    catch( Exception ex )
    {
        Console.WriteLine( "Error saving {0} - {1}", sFileName, ex.Message );
    }
    return false;
}

Conclusion

This is just too easy. I love .NET.

Comments Date
Home Search Contact us About us