I need convert image to Data URL (embedding Image) in the Win-application for HTML and I need Data URL (embedding Image) to image.
-
2The title does a better job of explaining the question the the actual question.– Jesper PalmCommented 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 ?– hashiCommented Jul 26, 2011 at 7:37
Add a comment
|
4 Answers
public static string GetDataURL(string imgFile)
{
return "<img src=\"data:image/"
+ Path.GetExtension(imgFile).Replace(".","")
+ ";base64,"
+ Convert.ToBase64String(File.ReadAllBytes(imgFile)) + "\" />";
}
-
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.– DaiCommented Jan 25, 2020 at 3:21
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")"/>
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"},
};