Wednesday, December 1, 2010

How to convert BMP to GIF in C#



In this post I will show you how to convert bmp file to gif in C#. First step you must do is create Bitmap object. In this example I passed filename to constructor of this object. Next you need to create ImageCodecInfo and chose appropriate mime type of output format. You can set quality and compression of output image. In case you need to do this, you must create EncoderParameters object which represents list of EncoderParameter objects. This objects represent set of parameters which encoder uses for image encoding.

static void Main(string[] args)
        {
            Bitmap myBitmap=new Bitmap(@"test.bmp");
            ImageCodecInfo myImageCodecInfo = GetEncoderInfo("image/gif"); ;
            EncoderParameter encCompressionrParameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionLZW); ;
            EncoderParameter encQualityParameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 0L);
            EncoderParameters myEncoderParameters = new EncoderParameters(2);
            myEncoderParameters.Param[0] = encCompressionrParameter;
            myEncoderParameters.Param[1] = encQualityParameter;
            myBitmap.Save("Output.gif", myImageCodecInfo, myEncoderParameters);
        }

        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;
        }

1 comment:

  1. I'm not a developer, I always use this free online image converter to convert bmp to gif online.

    ReplyDelete