Reputation: 4410
I am using puppeteersharp to converting HTML to image:
https://www.puppeteersharp.com/examples/index.html
This is getting the HTMl and save the image, then I am going to return base64 image, I am looking to return image base64 without saving it in hard drive.
This is the code:
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
var browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = true
});
var page = await browser.NewPageAsync();
await page.SetViewportAsync(new ViewPortOptions
{
Width = 750,
Height = 750,
});
await page.SetContentAsync("<h2>Test</h2>");
await page.ScreenshotAsync(@"/Users/myname/Documents/puppeteertests/test1.jpg");
byte[] b = System.IO.File.ReadAllBytes(@"/Users/myname/Documents/puppeteertests/test1.jpg");
return Convert.ToBase64String(b);
Upvotes: 1
Views: 1456
Reputation: 547
I am thinking something like this should probably work - It takes the Stream that gets returned by the 'ScreenshotStreamAsync' method of the page and copies it to a MemoryStream so that we can get a byte array out of it really simply and pass that byte array to the Convert.ToBase64String
var thing = await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
var browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = false
});
var page = await browser.NewPageAsync();
await page.SetViewportAsync(new ViewPortOptions
{
Width = 750,
Height = 750,
});
await page.SetContentAsync("<h2>Test</h2>");
await page.ScreenshotAsync(@"test1.jpg");
using (var memStream = new MemoryStream())
{
page.ScreenshotStreamAsync().Result.CopyTo(memStream);
var mything = Convert.ToBase64String(memStream.ToArray());
Console.WriteLine(mything);
}
Upvotes: 2