52

I need convert image to Data URL (embedding Image) in the Win-application for HTML and I need Data URL (embedding Image) to image.

2
  • 2
    The title does a better job of explaining the question the the actual question. Commented Jul 26, 2011 at 7:22
  • thanks Jeff , i have many image in the local disk , the images have different size some image is large and some image small , i need solution for some image convert to HTML and use in web browser ?
    – hashi
    Commented Jul 26, 2011 at 7:37

4 Answers 4

85
        public static string GetDataURL(string imgFile)
        {
            return "<img src=\"data:image/" 
                        + Path.GetExtension(imgFile).Replace(".","")
                        + ";base64," 
                        + Convert.ToBase64String(File.ReadAllBytes(imgFile)) + "\" />";
        }
1
  • 2
    Path.GetExtension(imgFile).Replace(".","") won't work if the file-extension does not match the file's actual content - I think the MIME Content-Type should be passed as a parameter.
    – Dai
    Commented Jan 25, 2020 at 3:21
33

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;
0
11

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")"/>
1

My Version:

string GetBase64Uri(string imgFile)
{
    var ext = Path.GetExtension(imgFile);
    if(dicSupportedFormats.TryGetValue(ext, out var typeStr))
        return $"<img src=\"data:image/{typeStr};base64,{Convert.ToBase64String(File.ReadAllBytes(imgFile))}\" />";
    else
        return null;
}

Dictionary<string, string> dicSupportedFormats = new Dictionary<string, string>{
    {".jpg", "jpeg"},
    {".jpeg", "jpeg"},
    {".jfif", "jpeg"},
    {".pjp", "jpeg"},
    {".pjpeg", "jpeg"},
    {".png", "png"},
    {".svg", "svg+xml"},
    {".webp", "webp"},
    {".gif", "gif"},
    {".avif", "avif"},
    {".apng", "apng"},
    {".ico", "x-icon"},
    {".cur", "x-icon"},
    {".tiff", "tiff"},
    {".tif", "tiff"},
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.