In this blog post, I will demonstrate how to embed image into HTML document.
Usually we provide image path to the src attribute of image tag.
<img src=” C:\SamplePictures\lighthouse.png” />
However there will be circumstances in web applications where you want to provide the HTML as downloadable content to the user. In such circumstances if the HTML document contains any external resources like Images, CSS etc., they will not be referenced/preserved along with the downloaded HTML document Hence the end user may not be viewing the appropriate document.
To achieve the integrity of the HTML document, external resources like images, CSS can be embedded into the document. This can be achieved in 2 steps.
Step 1: Create Base64 representation of Image
string base64 = Convert.ToBase64String(imageBytes); //This will convert the image bytes into base64 string.
Step 2: In the src attribute of image tag, provide image information in below format.
<img src="data:image/png;base64,iVBsafd .. .. ..”/>
Now open the document in browser, we can view the embedded image.
Data URI scheme:
Data URI scheme is a URI scheme that provides a way to include data in-line with web pages as if they were external resources. This allows images and style sheets to be fetched in single HTTP request rather than multiple HTTP request.
All major browsers like Firefox, Safari, Android, Chrome, IE8 and IE9 provide support for this data URI scheme.
Sample C# code snippet:
FileStream fs = new FileStream(<<ImagePath>>, FileMode.Open, FileAccess.Read);
byte imageBytes = new byte[fs.Length];
fs.Read(imageBytes, 0, imageBytes.Length);
StreamWriter streamWriter = new StreamWriter("test.html");
streamWriter.Write("<img src=\"data:image/"+ <<FileExtension>>
+ ";base64," + Convert.ToBase64String(imageBytes) + "\"/>");
For more information on this refer below links: