Skip to content

Instantly share code, notes, and snippets.

@iamphill

iamphill/file.cs

Created May 21, 2014
Embed
What would you like to do?
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
You can’t perform that action at this time.