Skip to content

Instantly share code, notes, and snippets.

@iamphill
Created May 21, 2014 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamphill/393642e94a65a06ec3d4 to your computer and use it in GitHub Desktop.
Save iamphill/393642e94a65a06ec3d4 to your computer and use it in GitHub Desktop.
C# data URI
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.IO;
using Umbraco.Core.Models;
using Umbraco.Core.Logging;
/// <summary>
/// Language switcher helper methods
/// </summary>
namespace PhCreative.BasePackage.Helpers
{
public static class LanguageSwitcherHelp
{
/// <summary>
/// Returns the data URL of an image
/// </summary>
/// <param name="media">Media IPublishedContent</param>
/// <returns>String with the data URI</returns>
public static string GetDataUrl(this IPublishedContent media)
{
string imgFile = null;
if (!String.IsNullOrEmpty(media.Url))
{
imgFile = System.Web.HttpContext.Current.Server.MapPath(media.Url);
}
if (String.IsNullOrEmpty(imgFile) || !System.IO.File.Exists(imgFile))
{
return String.Empty;
}
try
{
string dataUri = "data:image/" + Path.GetExtension(imgFile).Replace(".", "") + ";base64," + Convert.ToBase64String(System.IO.File.ReadAllBytes(imgFile));
return dataUri;
}
catch (System.IO.IOException ioex)
{
LogHelper.Error(typeof(LanguageSwitcherHelp), "Error getting data URI for " + media.Id, ioex);
return String.Empty;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment