Confessions of a .NET Developer!

Using Extension methods – Convert Image to Byte or Base64

Lot of people have questions like, how to convert an Image to byte array or to a Base64 string. I will solve these problems using the Extension methods feature.

With extension methods, you don’t have the need to use Inheritance to use the methods. An extension method is applied to a particular class or structure. An example can help understand more about it.
To start using Extension methods, firstly you need to create a static class which (obviously) will have static methods. In our example, two methods will be created, one which converts Image to byte array and another converts Image to Base 64 string.

    static class ExtensionClass
    {
        public static byte[] GetImageInBytes(this Image img, System.Drawing.Imaging.ImageFormat format)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                if (format != null)
                {
                    img.Save(ms, format);
                    return ms.ToArray();
                }
                else
                {
                    img.Save(ms, img.RawFormat);
                    return ms.ToArray();
                }
            }
        }

        public static string GetImageInBase64(this Image img, System.Drawing.Imaging.ImageFormat format)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                if (format != null)
                {
                    img.Save(ms, format);
                    return Convert.ToBase64String(ms.ToArray());
                }
                else
                {
                    img.Save(ms, img.RawFormat);
                    return Convert.ToBase64String(ms.ToArray());
                }
            }
        }
    }

The first parameter has “this” keyword which tells the compiler that “please add this method as an extension method to the Image class to be used by it’s object”. The second parameter takes the ImageFormat as parameter.

Let’s implement this.

    class Program
    {
        static string path = @"C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Sunset.jpg";
        static void Main(string[] args)
        {
            using (Image myImage = Image.FromFile(path))
            {
                //Extension method used here
                byte[] a = myImage.GetImageInBytes(System.Drawing.Imaging.ImageFormat.Gif);
            }

            using (Image myImage = Image.FromFile(path))
            {
                //Extension method used here also
                string s = myImage.GetImageInBase64(null);
            }
        }
    }

Simple to use, isn’t it. No need of inheritance.

When you type to find the extension method, you can see a down-arrow indicating an extension method.

ExtensionMethod

ExtensionMethod

June 29, 2011 Posted by | C Sharp | Leave a comment