Created
May 21, 2014 11:02
-
-
Save iamphill/393642e94a65a06ec3d4 to your computer and use it in GitHub Desktop.
C# data URI
This file contains hidden or 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.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