public static MvcHtmlString DataUriImage <T>(this HtmlHelper <T> htmlHelper, string image, IDictionary <string, object> htmlAttributes) { DataUriImage dataUriImage = GetDataUriImageFromCache(image, htmlHelper.ViewContext.HttpContext); var tb = GetTagbuilder(dataUriImage, htmlAttributes); return(MvcHtmlString.Create(tb.ToString(TagRenderMode.Normal))); }
private static TagBuilder GetTagbuilder(DataUriImage image, IDictionary <string, object> htmlAttributes) { TagBuilder tb = new TagBuilder("span"); tb.MergeAttributes(htmlAttributes); tb.MergeAttribute("style", string.Format(";width:{0}px;height:{1}px;display:inline-block;", image.Width, image.Height)); tb.MergeAttribute("class", image.Id); MothScriptHelper.RegisterDataUri(image.Id, image.ImageUrl); return(tb); }
internal static DataUriImage GetDataUriImageFromCache(string image, HttpContextBase httpContext) { return(Provider.GetFromCache("datauri." + image, () => { var img = new DataUriImage(); img.ImageUrl = image; byte[] buffer; Uri uri; if (Uri.TryCreate(image, UriKind.RelativeOrAbsolute, out uri) && uri.IsAbsoluteUri) { // download the file using (var wc = new WebClient()) { buffer = wc.DownloadData(uri); } } else { buffer = File.ReadAllBytes(httpContext.Server.MapPath("~/" + image.TrimStart('~').TrimStart('/'))); } using (var imageStream = new MemoryStream(buffer)) { var bitmap = Image.FromStream(imageStream); img.Width = bitmap.Width; img.Height = bitmap.Height; img.Type = GetStringFromImageType(bitmap.RawFormat); } img.Base64 = Convert.ToBase64String(buffer); img.Id = ""; while (img.Id.Length < 10) { img.Id += (char)('a' + Random.Next(26)); } return img; }, Provider.CacheDurations.DataUri)); }