Code to handle image data URIs

Aug 2, 2012 at 12:09 AM
Edited Aug 2, 2012 at 12:12 AM

CssValue doesn't handle data URIs which can be very handy for passing small images. The additional code to support them is small.

In CssValue::GetImage(string path):

Uri uri = source as Uri;

near the top and then, later:

else if (uri != null && uri.Scheme == "data")
{
    // parse the data URI:
    //   data:([mediatype])?(;base64)?,
    //   where [mediatype] is
    //      [type]/[subtype](;[param name]=[param value])*
    // Here, we only care about images so we look only for 
    // [type]="image" and ignore everything else. This means
    // we accept ill-formed data URIs but so do many browsers.
    string[] s = 
        uri.OriginalString.Substring(uri.OriginalString.IndexOf(':') + 1).Split(new[] { ',' }, 2);
    if (s.Length == 2)
    {
        var mediaTypeParametersAndBase64 = 
          s[0].Split(new[] { ';' }).Select(part => part.Trim().ToLower()).ToList();
        if (mediaTypeParametersAndBase64.Count(part => part.StartsWith("image/")) != 0)
        {
            byte[] imageData = mediaTypeParametersAndBase64.Count(part => part == "base64") != 0
                                   ? Convert.FromBase64String(s[1].Trim())
                                   : new System.Text.UTF8Encoding().GetBytes(
                                       Uri.UnescapeDataString(s[1].Trim()));
            return Image.FromStream(new MemoryStream(imageData));
        }
    }

    return null;
}

Developer
Nov 13, 2012 at 1:39 PM

fixed in 1.1.0.0

Feb 4, 2015 at 3:02 PM
Could it be possible to use a base64 uri as a background image also ?