Last active
January 21, 2018 10:19
-
-
Save hermanussen/5b0cc21a5a17da14db8fa2bcda2a219e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using Sitecore.Web.UI.WebControls; | |
using System.Web.UI; | |
using System.Net; | |
using Sitecore.Data.Fields; | |
namespace InlineImageRenderer | |
{ | |
/// <summary> | |
/// Convert a Sitecore image to an inline image. | |
/// </summary> | |
public class InlineImage : Image | |
{ | |
protected override void Render(HtmlTextWriter output) | |
{ | |
// use normal rendering so that you can get the URL | |
string img = RenderAsText(); | |
// parse the URL from the image tag | |
int srcIndex = ! string.IsNullOrEmpty(img) && img.IndexOf("src=\"") > 0 ? img.IndexOf("src=\"") + 5 : -1; | |
if (srcIndex > 0) | |
{ | |
string imgUrl = img.Substring(srcIndex, img.IndexOf('\"', srcIndex) - srcIndex); | |
string absoluteUri = System.Web.HttpContext.Current.Request.Url.AbsoluteUri; | |
string fullImgUrl = string.Format("{0}/{1}", absoluteUri.Substring(0, absoluteUri.IndexOf('/', absoluteUri.IndexOf("//") + 2)), imgUrl); | |
// download the image using WebClient | |
WebClient client = new WebClient(); | |
byte[] imgData = client.DownloadData(fullImgUrl); | |
if (imgData != null && imgData.Length > 0) | |
{ | |
// find the mime type as set on the item in the media library | |
ImageField imageField = FieldTypeManager.GetField(this.GetItem().Fields[Field]) as ImageField; | |
if (imageField != null) | |
{ | |
// write the image tag and replace the URL with the inline image data | |
output.Write(img.Substring(0, srcIndex)); | |
output.Write(string.Format("data:{0};base64,{1}", imageField.MediaItem.Fields["Mime Type"].Value, Convert.ToBase64String(imgData))); | |
output.Write(img.Substring(srcIndex + imgUrl.Length)); | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment