Converting an image binary in string to a stream

We have a feature that allows users to create notes on content within the system – akin to adding a note to a textbook, but with a whole lot more space than a textbook. As part of our microservice initiative, I’m moving this functionality out into a separate service which will store its data in Cosmos instead of a SQL database.

One of the issues we currently have this functionality is that a user can embed images into their notes and these images are represented in the HTML image tag by a binary string. So something like:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUh....hAAAAAElFTkSuQmCC" alt="" width="659" height="556" />

Note: The does represent a lot of missing characters because these strings can be long.

The problem we have is that these can become very large. Obviously there is the concern about the database holding such large pieces of data in text, but it provide a sub-optimal experience for the users because they are slow to download – the whole note including image has be downloaded before any of the note is visible and there is no caching of the images. Plus some of these have caused near breaking issues for our mobile applications.

So, as part of this project I am pulling these binary strings out, recreating the binary object in memory, and then storing that object in an Azure Storage blob. I could not find a good source online of how to do this, so here is what I came up with:

var bytes = Convert.FromBase64String(image);
using (MemoryStream stream = new MemoryStream(bytes))
	// Do what you need with the memory stream

I wrote a bigger sample which does the whole process I needed:

  • Parse each image tag in an HTML document which has an image represented in a binary string
  • Convert the binary string to a memory stream
  • Upload that memory stream to an Azure Storage blob container
  • Change the image src attribute value to point to the URL of the Azure Storage blob container

You can find the complete sample at

Hope that helps you out!