Return 使用 puppeteersharp 的 base 64 图像,不将文件保存在硬盘中
Return Image base 64 without saving the file in hard drive, using puppeteersharp
我正在使用 puppeteersharp 将 HTML 转换为图像:
https://www.puppeteersharp.com/examples/index.html
这是获取 HTMl 并保存图像,然后我要 return base64 图像,我正在寻找 return 图像 base64 而不将其保存在硬盘中。
这是代码:
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);
我在想这样的事情应该可行 -
它获取由页面的 'ScreenshotStreamAsync' 方法返回的 Stream 并将其复制到 MemoryStream 以便我们可以非常简单地从中获取字节数组并将该字节数组传递给 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);
}
我正在使用 puppeteersharp 将 HTML 转换为图像:
https://www.puppeteersharp.com/examples/index.html
这是获取 HTMl 并保存图像,然后我要 return base64 图像,我正在寻找 return 图像 base64 而不将其保存在硬盘中。
这是代码:
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);
我在想这样的事情应该可行 - 它获取由页面的 'ScreenshotStreamAsync' 方法返回的 Stream 并将其复制到 MemoryStream 以便我们可以非常简单地从中获取字节数组并将该字节数组传递给 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);
}