Posts Tagged 'Base64 Images'

C# How to: Encoding Base64 Thumbnails

Article purpose

This details how to read files from the file system, create and then encoding to strings.

Sample source code

This is accompanied by a sample source code Visual Studio project which is available for download .

Images as Base64 strings

From :

Base64 is a group of similar encoding schemes that represent in an ASCII string format by translating it into a -64 representation. The Base64 term originates from a specific .

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 via , and storing complex data in .

From the definition quoted above the need for base64 encoding becomes more clear. From :

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.

encoding allows developers to expose binary data without potentially encountering conflicts in regards to the transfer medium. encoded binary data serves ideally when performing data transfer operations using platforms such as html, xml, email.

A common implementation of encoding can be found when transferring data. This article details how to convert/encode object to strings.

Base64 Image encoding implemented as an extension method

The code snippet listed below details the ToBase64String targeting the class.

public static string ToBase64String(this Image bmp)
{
    string base64String = string.Empty;
    MemoryStream memoryStream = null;

try { memoryStream = new MemoryStream(); bmp.Save(memoryStream, ImageFormat.Png); } catch (Exception exc) { return String.Empty; }
memoryStream.Position = 0; byte[] byteBuffer = memoryStream.ToArray();
memoryStream.Close();
base64String = Convert.ToBase64String(byteBuffer, Base64FormattingOptions.InsertLineBreaks); byteBuffer = null;
return base64String; }

The ToBase64String method writes the targeted object’s pixel data to a object using the Png . Next a array is extracted and passed to the method , which is responsible for implementing the encoding.

Creating an Image tag implementing a Base64 string

The sample source code in addition also defines an to generate html image tags to display a string encoded .

public static string ToBase64ImageTag(this Image bmp)
{
    string imgTag = string.Empty;
    string base64String = string.Empty;

base64String = bmp.ToBase64String();
imgTag = "<img src=\\"data:image/" + "png" + ";base64,"; imgTag += base64String + "\\" "; imgTag += "width=\\"" + bmp.Width.ToString() + "\\" "; imgTag += "height=\\"" + bmp.Height.ToString() + "\\" />";
return imgTag; }

The ToBase64ImageTag invokes the ToBase64String in order to retrieve encoded the data. The Html image tag has only to be slightly modified from the norm in order to accommodate encoded strings.

Creating Image thumbnails

The class conveniently provides the method , which we’ll be using to create from existing objects. The sample source code defines the method ToBase64Thumbnail, as listed below:

public static string ToBase64Thumbnail(this Image bmp, int width, int height, bool wrapImageTag)
{
    Image.GetThumbnailImageAbort callback = new Image.GetThumbnailImageAbort(ThumbnailCallback);

Image thumbnailImage = bmp.GetThumbnailImage(width, height, callback, new IntPtr());
string base64String = String.Empty;
if (wrapImageTag == true) { base64String = thumbnailImage.ToBase64ImageTag(); } else { base64String = thumbnailImage.ToBase64String(); }
thumbnailImage.Dispose();
return base64String; }
private static bool ThumbnailCallback() { return true; }

The ToBase64Thumbnail is defined as an targeting the class. The calling code is required to specify the width and height of the output and in addition whether to wrap the encoded string in an Html <img> tag.

Note the definition of ThumnailCallback, the method requires calling code to specify a callback delegate.

Based on the value of the parameter wrapImageTag, we next invoke either ToBase64ImageTag or ToBase64String, as defined/discussed earlier.

Reading Image files from the file system

The starting point in creating encoded would be to read the local file system, searching for files. The ToBase64Thumbnails method is defined as an targeting the string class. When invoking the ToBase64Thumbnails method users are expected to provide a directory path, width and height of output , whether to add Html <img> tags and which file types to process. The code snippet below details the implementation of the ToBase64Thumbnails method.

public static List<string> ToBase64Thumbnails(this string path, int width, int height, bool wrapImageTag, params string[] fileTypes)
{
    List<string> base64Thumbnails = new List<string>();

string searchFilter = String.Empty;
if (fileTypes != null) { for (int k = 0; k < fileTypes.Length; k++) { searchFilter += "*." + fileTypes[k];
if (k < fileTypes.Length - 1) { searchFilter += "|"; } } } else { searchFilter = "*.*"; }
string[] files = Directory.GetFiles(path, searchFilter);
for (int k = 0; k < files.Length; k++) { StreamReader streamReader = new StreamReader(files[k]); Image img = Image.FromStream(streamReader.BaseStream); streamReader.Close();
base64Thumbnails.Add(img.ToBase64Thumbnail(width, height, wrapImageTag));
img.Dispose(); }
return base64Thumbnails; }

The ToBase64Thumbnails method implements the static method in order to search a specified directory path. When invoking the ToBase64Thumbnails method the calling code can optionally specify a number of file extensions, which results in only files having file extensions conforming to the specified extensions being encoded.

Once an array of file paths have been determined the sample code iterates the array creating an object of each file specified. The final step required is to invoke the ToBase64Thumbnail.

The implementation

The sample source code defines a console based application, used to test/illustrate creating encoded based on a specified directory path.  Included in the sample code is a template html file. The Main method generates a list of encoded by invoking ToBase64Thumbnails, defined as an targeting the String class. The resulting encoded are defined as Html <img> tags, added to a copy of the html template file. The Console application’s definition:

static void Main(string[] args)
{
    string path = "Images";

List<string> thumbnailTags = path.ToBase64Thumbnails(100, 100, true, null);
StreamReader streamreader = new StreamReader("HtmlTemplate.htm"); StringBuilder htmlPage = new StringBuilder(streamreader.ReadToEnd()); streamreader.Close();
StringBuilder imageTags = new StringBuilder();
for (int k = 0; k < thumbnailTags.Count; k++) { imageTags.AppendLine("<p>"); imageTags.AppendLine(thumbnailTags[k]); imageTags.AppendLine("</p>"); }
htmlPage.Replace("<!--Tags_Placeholder-->", imageTags.ToString());
StreamWriter streamwriter = new StreamWriter("TempPage.htm", false, Encoding.UTF8); streamwriter.Write(htmlPage.ToString()); streamwriter.Close();
Process.Start("TempPage.htm");
Console.ReadKey(); }

The resulting encoded image viewed as html <img> tags forming part of an html file, as viewed in Microsoft Internet Explorer 9:

Base64Thumbnails

C# How to: Decoding/Converting Base64 strings to Bitmap images

Article purpose

This details how to decode or convert encoded back into by means of the class.

Note: This article is an update that builds upon the article:

Sample source code

This is accompanied by a sample source code Visual Studio project which is available for download .

Images as Base64 strings

From :

Base64 is a group of similar encoding schemes that represent in an ASCII string format by translating it into a -64 representation. The Base64 term originates from a specific .

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 encoding becomes more clear. From :

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.

encoding allows developers to expose without potentially encountering conflicts in regards to the transfer medium. encoded serves ideally when performing data transfer operations using platforms such as html, json, rest, xml, email.

A common implementation of encoding can be found when transferring data. This details how to convert/decode a back into a Bitmap .

Base64 String to Bitmap decoding implemented as an extension method

The code snippet listed below details the Base64StringToBitmap targeting the .

public static Bitmap Base64StringToBitmap(this string
                                           base64String)
{
    Bitmap bmpReturn = null;

byte[] byteBuffer = Convert.FromBase64String(base64String); MemoryStream memoryStream = new MemoryStream(byteBuffer);
memoryStream.Position = 0;
bmpReturn = (Bitmap)Bitmap.FromStream(memoryStream);
memoryStream.Close(); memoryStream = null; byteBuffer = null;
return bmpReturn; }

The parameter is first converted to a array by invoking the method. Next we create a against the resulting array, which serves as a parameter to the class’ static method.

The implementation

The Base64StringToBitmap is implemented in a console based application. The creates a instance from the local file system, which is then converted to a .

An article detailing how to convert to encoded can be found here:

– The you are currently reading was published as a follow up .

Next the newly created is converted back to a by invoking the Base64StringToBitmap . In order to test if the was decoded successfully the is saved to the local file system and displayed in the default installed application associated with png . The implementation as follows:

static void Main(string[] args)
{
    StreamReader streamReader = new StreamReader(
                                   "NavForward.png");

Bitmap bmp = new Bitmap(streamReader.BaseStream); streamReader.Close();
string base64ImageString = bmp.ToBase64String( ImageFormat.Png);
Console.WriteLine(base64ImageString);
Bitmap bmpFromString = base64ImageString.Base64StringToBitmap();
bmpFromString.Save("FromBase64String.png", ImageFormat.Png);
Process.Start("FromBase64String.png");
Console.ReadKey(); }

Related Articles and Feedback

Feedback and questions are always encouraged. If you know of an alternative implementation or have ideas on a more efficient implementation please share in the comments section.

Dewald Esterhuizen

I’ve published a number of articles related to imaging and images of which you can find URL links here:

C# How to: Encoding Bitmaps to Base64 strings

Article purpose

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 .

Images as Base64 strings

From :

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 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 class.

public static string ToBase64String(this Bitmap bmp, ImageFormat imageFormat)
{
    string base64String = string.Empty;

MemoryStream memoryStream = new MemoryStream(); bmp.Save(memoryStream, imageFormat);
memoryStream.Position = 0; byte[] byteBuffer = memoryStream.ToArray();
memoryStream.Close();
base64String = Convert.ToBase64String(byteBuffer); byteBuffer = null;
return base64String; }

The ToBase64String method writes the targeted object’s pixel data to a object using the specified parameter. Next a byte array is extracted and passed to the method , 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.

 public static string ToBase64ImageTag(this Bitmap bmp, ImageFormat imageFormat)
{
    string imgTag = string.Empty;
    string base64String = string.Empty;

base64String = bmp.ToBase64String(imageFormat);
imgTag = "<img src=\\"data:image/" + imageFormat.ToString() + ";base64,"; imgTag += base64String + "\\" "; imgTag += "width=\\"" + bmp.Width.ToString() + "\\" "; imgTag += "height=\\"" + bmp.Height.ToString() + "\\" />";
return imgTag; }

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 implementation

The two extension methods are implemented using a console based application.

 static void Main(string[] args)
{
    StreamReader streamReader = new StreamReader("NavForward.png");
    Bitmap bmp = new Bitmap(streamReader.BaseStream);
    streamReader.Close();

string base64ImageAndTag = bmp.ToBase64ImageTag(ImageFormat.Png);
Console.WriteLine(base64ImageAndTag);
Console.ReadKey(); }

Dewald Esterhuizen

Blog Stats

  • 462,971 hits

Enter your email address to follow and receive notifications of new posts by email.

Join 210 other followers

Archives

Twitter feed


%d bloggers like this: