how to convert Image to Data URI for Html with C#?

Viewed 33942

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

4 Answers

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"},
};
Related