Monday, October 1, 2007

How to convert image between different format?

/// <summary>
/// Convert image file to certain format
/// </summary>
/// <param name="fromImageFullPath">The original image file</param>
/// <param name="toImageFullPath">The new image file</param>
/// <param name="mimeType">The format of the new image file, i.e. "image/bmp", "image/jpeg"</param>
public static void ConvertImage(string fromImageFullPath, string toImageFullPath, string mimeType)
{
try
{
// Read the content of the image file into a bitmap variable
Stream fromFile = File.OpenRead(fromImageFullPath);
Image image = Image.FromStream( fromFile, true ) ;
Bitmap bitmap = (Bitmap) image;
// Instantiate the encoder
EncoderParameters encoderParams = new EncoderParameters();
encoderParams.Param[0] = new EncoderParameter( Encoder.Quality, 50L );
ImageCodecInfo codecInfo = GetEncoderInfo( mimeType );
// Covert the image to the new format
MemoryStream newImage = new MemoryStream();
bitmap.Save( newImage, codecInfo, encoderParams );
// Write the new image into a file
byte[] data = newImage.ToArray();
Stream toFile = File.OpenWrite( toImageFullPath );
toFile.Write(data,0,data.GetLength(0));
fromFile.Close();
toFile.Close();
}
catch(Exception ex)
{
...
}
}



/// <summary>
/// Get encoder infor
/// </summary>
/// <param name="mimeType">the codec's Multipurpose Internet Mail Extensions (MIME) type</param>
/// <returns>All pertinent information about the installed image codecs</returns>
private static ImageCodecInfo GetEncoderInfo(String mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for(j = 0; j < encoders.Length; ++j)
{
if(encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}

No comments:

Post a Comment