How to have your asp.net site convert images to embedable strings.

C#

C# code to encode images into HTML

private string CreateBase64Image(byte[] fileBytes)
{
    Image streamImage;

    using (MemoryStream ms = new MemoryStream(fileBytes))
    {
        /* Create a new image, saved as a scaled version of the original */
        streamImage = ScaleImage(Image.FromStream(ms));
    }

    using (MemoryStream ms = new MemoryStream())
    {
        /* Convert this image back to a base64 string */
        streamImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return Convert.ToBase64String(ms.ToArray());
    }
}

How to embed these image into CSS

<style type="text/css" >
    div.my-image { width:150px;
    height:150px;
    background-image: url("data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABA......");
    }
</style>

How to embed these images into HTML

    <img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABA......" />

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.