Embedding images directly into HTML with C#

The usual approach is to reference an image using the image name. But it is also possible to embed the image directly into a webpage. This is especially useful for report generation where it is required to move the report files from one location to another. Embedding an image into the webpage ensures you don’t run into problems where the referenced image is no longer on the system.
Note: Embedding works well for smaller file sizes.

Here’s how you can embed an image directly into a webpage: Get a Base64 representation of the image file, append a few more string characters to it and simply set it as the value of the src attribute.

1. The first step is to get a Base64 representation of the image (Remember to add a reference to System.Drawing and System.IO namespaces)


            using (Image img = Image.FromFile(imgpath))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    img.Save(ms, img.RawFormat);
                    byte[] imgBytes = ms.ToArray();
                    return Convert.ToBase64String(imgBytes);
                }
            }

2. Before the string can be assigned to the src tag in your, you need to provide additional information for the browser to understand and render the image content. The following code creates the remaining string content to go to the front of base64 representation of the string, and supports any file type.


string initialContent = "data:image/" + Path.GetExtension(imgpath).TrimStart('.') + ";base64,";

And it should look something like this when you put the required html tags around it:


<img src="data:image/png;base64,kMIPRd8VQgmA....." alt="Loading Image">

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>