Saturday, 14 September 2013

Embedding Image Data in CSS with System.Web.Optimization

Embedding Image Data in CSS with System.Web.Optimization

I have been searching all day reading articles, blogs, forums about this,
but either I'm not understanding it well or I truly haven't found the
answer.
On my site, I have implemented microsft.web.optimization v.1.0.0 and found
an extension method below (which can be found at Optimizing without
drawbacks):
public class CssImageEmbedTransform : CssMinify {
private static readonly Regex url = new
Regex(@"url\((([^\)]*)\?embed)\)", RegexOptions.IgnoreCase);
private const string format = "url(data:image/{0};base64,{1})";
public override void Process(BundleResponse bundle) {
base.Process(bundle);
string reference = HttpContext.Current.Request.ApplicationPath +
"includes/css/";
// Before Using BundleTable to ResolveUrl in head control
// HttpContext.Current.Request.Path.Replace("/barry.css", "/");
// debug stuff
// HttpContext.Current.Response.Write("<br />Before Matches<br />");
//
HttpContext.Current.Response.Write(url.Matches(bundle.Content).Count
+ "<br />");
foreach (Match match in url.Matches(bundle.Content)) {
var file = new FileInfo(HostingEnvironment.MapPath(reference +
match.Groups[2].Value));
if (file.Exists) {
string dataUri = GetDataUri(file);
bundle.Content = bundle.Content.Replace(match.Value,
dataUri);
HttpContext.Current.Response.AddFileDependency(file.FullName);
}
}
// debug stuff
// HttpContext.Current.Response.Write("After Matches");
// HttpContext.Current.Response.End();
}
private string GetDataUri(FileInfo file) {
byte[] buffer = File.ReadAllBytes(file.FullName);
string ext = file.Extension.Substring(1);
return string.Format(format, ext, Convert.ToBase64String(buffer));
}
}Along with this code:
private void SetupBundles() {
BundleTable.Bundles.EnableDefaultBundles();
Bundle css = new Bundle("~/mycc.css",
typeof(CssImageEmbedTransform));
css.AddFile("~/includes/css/mycss.css");
BundleTable.Bundles.Add(css);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}What that did was convert background-image:
url(Images/myImage.png?embed); to background-image:
url(data:image/png;base64,iVBORw0KGgoA...lFTkSuQmCC);.
I have recently updated my site to use system.web.optimization v.1.1.0
(found at Bundling and Minification) and I'm wondering if there is
something similar or better (maybe built-in) to accomplish the same?
Thanks!

No comments:

Post a Comment