/// <summary> /// Corrects all relative image paths inside a style sheet to turn them into full paths /// in order to allow for these style sheets to work when combined into one file. /// Also, if 'rewriteImagePaths' is true, prepends a subdomain to all image paths in the css file. /// </summary> /// <param name="cssContent">The contents of the css file</param> /// <param name="cssFilePath">The path of the css file</param> /// <param name="rewriteImagePaths">If true will prepend a subdomain to all image paths in this css</param> /// <param name="imagesHostToPrepend">The subdomain to prepend to the image paths</param> /// <returns></returns> private static string FixImagePaths(string cssContent, string cssFilePath, bool rewriteImagePaths, string imagesHostToPrepend) { var processedUrls = new Dictionary <string, string>(); var imgRgx = new Regex(@"(?<=url\().*?\)"); MatchCollection imgMatches = imgRgx.Matches(cssContent); foreach (Match imgM in imgMatches) { string url = imgM.ToString().Replace(")", "").Replace("\"", "").Replace("'", "").Trim(); if (string.IsNullOrEmpty(url) || processedUrls.ContainsKey(url)) { continue; } processedUrls.Add(url, url); var rgxUsedToReplaceInCss = new Regex(@"\(\s*[""']{0,1}" + url + @"[""|']{0,1}\s*\)"); // correct the image path relative to the cssFilePath (if doesn't start with /cms) string correctedImgPath = ImagePathsUtility.CorrectUrl(url, cssFilePath); if (rewriteImagePaths && !ImagePathsUtility.IsFont(url)) { // forward slash in the beginning not required here, since this will be an absolute path correctedImgPath = string.Format("{0}/{1}", imagesHostToPrepend, correctedImgPath.TrimStart('/')); } cssContent = rgxUsedToReplaceInCss.Replace(cssContent, "(" + correctedImgPath + ")"); } return(cssContent); }
protected override void Process2(ref CombinerFilterContext data) { if (!data.PrependCdnHostToImages || string.IsNullOrEmpty(data.CdnHostToPrepend)) { return; } if (Images == null) { return; } foreach (HtmlNode img in Images) { var url = img.Attributes["src"].Value; if (string.IsNullOrEmpty(url) || url.StartsWith("http")) { continue; } // correct the image path relative to the requested page path (if doesn't start with /cms) string correctedImgPath = ImagePathsUtility.CorrectUrl(url, data.RequestPath); url = string.Format("{0}/{1}", data.CdnHostToPrepend, correctedImgPath.TrimStart('/')); img.Attributes["src"].Value = url; } }