How to Convert Image to Data Uri for HTML with C#

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

        public static string GetDataURL(string imgFile)
{
return "<img src=\"data:image/"
+ Path.GetExtension(imgFile).Replace(".","")
+ ";base64,"
+ Convert.ToBase64String(File.ReadAllBytes(imgFile)) + "\" />";
}

Detect data URI in image src using HtmlAgilityPack

HtmlAgilityPack doesn't have built-in function to detect data URI, so you still need to incorporate your own implementation of such function.

As an aside, you can use LINQ API of HtmlAgilityPack to select img element that have reference src attribute in the first place :

var referenceImgs = htmlDoc.DocumentNode
.Descendants("img")
.Where(o => !StringIsDataUri(o.GetAttributeValue("src","")));

foreach(HtmlNode img in referenceImgs)
{
Console.WriteLine("BASE ENCODE THE REFERENCED FILE");
}

Render HTML as an Image on the backend and Convert to Base64 string

Sounds like you need a HTML renderer. I don't think there is a easy or simple way to do this, especially if there is dynamic content.
You're best pick would be something like puppeteersharp

public static void ExportPage() {
await using var page = await browser.NewPageAsync();
await page.SetContentAsync("<div>My Receipt</div>");
var result = await page.GetContentAsync();
page.ScreenshotAsync(myPath);
}

URI to Bitmap C# ASP.NET

[HttpPost]
public JsonResult Scan(string file)
{
byte[] data = Convert.FromBase64String(file.Substring(file.LastIndexOf(',') + 1));
Image image;
Bitmap bitmap;
using (MemoryStream ms = new MemoryStream(data))
{
image = Image.FromStream(ms);
bitmap = new Bitmap(image);
}
}


Related Topics



Leave a reply



Submit