.Net Image as HTML embedded Picture

Tags: base64

Sometimes you may find it usefull to convert a .Net Image as embedded HTML picture.
This can be usefull when creating HTML content that should be displayed offline or transmitted as Email.
How does it work?
Basically we found out that in HTML an embedded picture works only as MIME-type “img/jpeg”.
So in any case the Image instance has to be converted into a JPEG-Image.
HTML is a Text-Language, so any binary content has to converted into Text, this is done using Base64 encoding.
Unfortunately a JPEG-Image has no transparency, and when creating a new Image that background-color is black.
So an easy solution is to create a new Bitmap with the same size of the original image, and fill the background with a solid color.
When converting the existing Image you should define the quality of the conversion, or the result could be a bit crappy.
The following functions will convert an Image into a complete Base64 encoded string.

private static string EncodeTo64(Image image) {
    byte[] data = ConvertImageToByteArray(image);
    return "data:image/jpeg;base64," + System.Convert.ToBase64String(data);
}

private static EncoderParameters GetEncoderParameters() {
    var parameters = new EncoderParameters(1);
    parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
    return parameters;
}

private static readonly ImageCodecInfo CodecInfo = ImageCodecInfo.GetImageEncoders().First(e => e.MimeType == "image/jpeg");

private static byte[] ConvertImageToByteArray(Image image) {
    using (MemoryStream ms = new MemoryStream()) {

        // Neues Bitmap nötig, da bei transparenten hintergründen -> schwarz
        // Deshalb einfach Bild auf weiße Fläche malen und als jpeg speichern.
        // Embedded Images funktioniert nur als jpeg
        Bitmap newImage = new Bitmap(image.Width, image.Height);
        Graphics g = Graphics.FromImage(newImage);
        g.FillRectangle(new SolidBrush(Color.White), new Rectangle(0, 0, newImage.Width, newImage.Height));
        g.DrawImageUnscaled(image, 0, 0);
        g.Dispose();
        newImage.Save(ms, CodecInfo, GetEncoderParameters());
        return ms.ToArray();
    }

}

Greets – Helmut

Add a Comment