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

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......" />
Advertisements
This entry was posted in ASP.NET, Brian's Code Extreme, C#, C-Langs, CSS, HTML. Bookmark the permalink.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s