JavaScript base64 image to Bitmap in C#

Converting base64 image string to Bitmap in C#

Base64 serialized images are useful in many cases for serving images on page. It is also a format of image that JavaScript can generate on the fly.

HTML canvas object has native support for base64 and it can be easily serialized to base64 string from JavaScript code by invoking toDataURL method of the canvas element.

As you can see in this sample, JavaScript generates base64 string serialized canvas object, but there is additional prefix:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJYAAACWCAYAAAA8AXHiAAAU....

This string prefix is not part of image base64 data, therefore before you try to convert it to Bitmap instance in C# code, you need to get rid of it. This can be easily done with simple regular expression:

public static String GetBase64FromJavaScriptImage(String javaScriptBase64String)
        {
            return Regex.Match(javaScriptBase64String, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
        }

    

Now we got rid of the JavaScript prefix, but this prefix is not completely useless. You can see that it holds the image format, which is by default png but can be changed with JavaScript and it depends on the browser support to encode canvas to specific image format. This can be also extracted with regular expression:

        public static String GetImageTypeFromJavaScriptImage(String javaScriptBase64String)
        {
            return Regex.Match(javaScriptBase64String, @"data:image/(?<type>.+?);(?<base64>.+?),(?<data>.+)").Groups["type"].Value;
        }

    
Note

How to get and actual instance of System.Drawing.Imaging.ImageFormat from a string you can find in article listed in the references sections at the bottom of this page

And now for the final thing and that is getting the Bitmap instance from the cleaned up base64 string data we just need to convert our base64 to byte array and pump it into the Stream from which we initialize the Bitmap instance

public static Bitmap GetBitmapFromBase64(string base64)
{
return new Bitmap(new MemoryStream(Convert.FromBase64String(Common.GetBase64FromJavaScriptImage(base64))));
        }

    

References

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.


About the author

DEJAN STOJANOVIC

Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform includion ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article