49

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

hashi
  • 2,520
  • 3
  • 22
  • 25
  • 2
    The title does a better job of explaining the question the the actual question. – Jesper Palm Jul 26 '11 at 07: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 Jul 26 '11 at 07:37

4 Answers4

83
        public static string GetDataURL(string imgFile)
        {
            return "<img src=\"data:image/" 
                        + Path.GetExtension(imgFile).Replace(".","")
                        + ";base64," 
                        + Convert.ToBase64String(File.ReadAllBytes(imgFile)) + "\" />";
        }
SimonGoldstone
  • 5,096
  • 3
  • 27
  • 38
Ankur
  • 33,367
  • 2
  • 46
  • 72
  • 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 Jan 25 '20 at 03:21
32

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;
Jesper Palm
  • 7,170
  • 31
  • 36
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")"/>
Community
  • 1
  • 1
Yuriy Silvestrov
  • 422
  • 4
  • 10
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"},
};
dovid
  • 6,354
  • 3
  • 33
  • 73