how to convert Image to Data URI for Html with C#?
I need convert image to Data URL (embedding Image) in the Win-application for HTML and I need Data URL (embedding Image) to image.
public static string GetDataURL(string imgFile)
{
return "<img src=\"data:image/"
+ Path.GetExtension(imgFile).Replace(".","")
+ ";base64,"
+ Convert.ToBase64String(File.ReadAllBytes(imgFile)) + "\" />";
}
Isn't a data URL just the image base 64 encoded?
Then this should do it.
var bytes = File.ReadAllBytes("C:\\somepath\\picture.png");
var b64String = Convert.ToBase64String(bytes);
var dataUrl = "data:image/png;base64," + b64String;
If you're using ASP.NET MVC, a bit revealed code from Ankur's answer could be more convinient:
public static string DataUriContent(this UrlHelper url, string path)
{
var filePath = HttpContext.Current.Server.MapPath(path);
var sb = new StringBuilder();
sb.Append("data:image/")
.Append((Path.GetExtension(filePath) ?? "png").Replace(".", ""))
.Append(";base64,")
.Append(Convert.ToBase64String(File.ReadAllBytes(filePath)));
return sb.ToString();
}
and the usage (just replacing @Url.Content
with @Url.DataUriContent
):
<img src="@Url.DataUriContent("~/Path/To/Image/yourImage.png")"/>