This article explores encoding Bitmap images to Base64 strings. Encoding is implemented by means of an extension method targeting the Bitmap class.
Sample source code
This article is accompanied by a sample source code Visual Studio project which is available for download here.
Images as Base64 strings
Base64 is a group of similar encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The Base64 term originates from a specific MIME content transfer encoding.
Base64 encoding schemes are commonly used when there is a need to encode binary data that need to be stored and transferred over media that are designed to deal with textual data. This is to ensure that the data remain intact without modification during transport. Base64 is commonly used in a number of applications including email via MIME, and storing complex data in XML.
From the definition quoted above the need for base64 encoding becomes more clear. From MSDN documentation:
The base-64 digits in ascending order from zero are the uppercase characters "A" to "Z", the lowercase characters "a" to "z", the numerals "0" to "9", and the symbols "+" and "/". The valueless character, "=", is used for trailing padding.
Base64 encoding allows developers to expose binary data without potentially encountering conflicts in regards to the transfer medium. Base64 encoded binary data serves ideally when performing data transfer operations using platforms such as html, xml, email.
A common implementation of Base64 encoding can be found when transferring image data. This article details how to convert/encode a Bitmap object to a Base64 string.
Base64 Bitmap encoding implemented as an extension method
The code snippet listed below details the ToBase64String extension method targeting the Bitmap class.
The ToBase64String method writes the targeted Bitmap object’s pixel data to a MemoryStream object using the specified ImageFormat parameter. Next a byte array is extracted and passed to the method Convert.ToBase64String, which is responsible for implementing the Base64 encoding.
Creating an Image tag implementing a Base64 string
The sample source code in addition also defines an extension method to generate html image tags to display a Base64 string encoded image.
The ToBase64ImageTag extension method invokes the ToBase64String extension method in order to retrieve encoded the data. The Html image tag has only to be slightly modified from the norm in order to accommodate Base64 encoded strings.
The two extension methods are implemented using a console based application.