使用asp.net core拍摄全页快照

问题描述 投票:0回答:1

公共异步任务CaptureFullPageScreenshot(字符串url,字符串输出路径) { 尝试 { 等待新的 BrowserFetcher().DownloadAsync(BrowserTag.Latest);

      using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))
      using (var page = await browser.NewPageAsync())
      {
          await page.GoToAsync(url, WaitUntilNavigation.Networkidle2);
          await page.SetViewportAsync(new ViewPortOptions { Width = 1349});

          int totalHeight = Convert.ToInt32(await page.EvaluateExpressionAsync("document.body.scrollHeight"));

          await page.SetViewportAsync(new ViewPortOptions { Width = 1349, Height = totalHeight });

          await page.ScreenshotAsync(outputPath);
      }
  }
  catch (Exception ex)
  {
      _logger.LogError($"Error while taking screenshot of '{url}' getting exception {ex.Message}");
  }
  finally {
      _logger.LogError($"screenshot captured successfully and stored at '{outputPath}'");
  }

}

上面是工作代码,只是想优化图像而不损失质量和尺寸。

image asp.net-core web-scraping puppeteer snapshot
1个回答
0
投票

我建议使用WebP格式,这样可以在不牺牲图像质量的情况下减小文件大小。

测试结果

在线检查图像:https://squoosh.app/editor

WebP 格式

原始格式

    public async Task CaptureFullPageScreenshot(string url, string outputPath)
    {
        try
        {
            await new BrowserFetcher().DownloadAsync(BrowserTag.Latest);
            using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true, ExecutablePath = @"C:\Program Files\Google\Chrome\Application\chrome.exe" }))
            using (var page = await browser.NewPageAsync())
            {
                await page.GoToAsync(url, WaitUntilNavigation.Networkidle2);
                await page.SetViewportAsync(new ViewPortOptions { Width = 1349 });

                int totalHeight = Convert.ToInt32(await page.EvaluateExpressionAsync("document.body.scrollHeight"));
                await page.SetViewportAsync(new ViewPortOptions { Width = 1349, Height = totalHeight });

                // save as PNG temporary
                var tempPath = Path.ChangeExtension(outputPath, ".png");
                await page.ScreenshotAsync(tempPath);

                // convert to WebP
                await ConvertToWebP(tempPath, outputPath);

                // delete tmp PNG file
                System.IO.File.Delete(tempPath);
            }
        }
        catch (Exception ex)
        {
            _logger.LogError($"Error while taking screenshot of '{url}' getting exception {ex.Message}");
        }
        finally
        {
            _logger.LogError($"Screenshot captured successfully and stored at '{outputPath}'");
        }
    }

    private async Task ConvertToWebP(string inputPath, string outputPath)
    {
        using (var image = await Image.LoadAsync(inputPath))
        {
            var encoder = new WebpEncoder
            {
                Quality = 75 // accoding your needs to adjust the Quality 
            };
            await image.SaveAsWebpAsync(outputPath, encoder);
        }
    }

我的测试网址:

https://localhost:7143/Snapshot/CaptureFullPageScreenshot?url=https://localhost:7143/Home/Privacy&outputPath=E:/abc_webp.jpg
© www.soinside.com 2019 - 2024. All rights reserved.