缩小无头傀儡截图的大小

Reduce size of headless puppeteer screenshot

我正在使用 lambda 函数启动无头人偶 chrome。我可以拍照并将其保存到 s3 存储桶中,但图像太大了。我最初将视口设置为默认值,但图像仍然显示为 1520 X 1520。

这是我当前启动无头浏览器并截取屏幕截图的代码。

const browser = await chromium.puppeteer.launch({
  executablePath: await chromium.executablePath,
  headless: chromium.headless,
  args: chromium.args,
  defaultViewport: { width: 800, height: 600, deviceScaleFactor: 2 },
  ignoreHTTPSErrors: true,
});
    
const body = isJson(event.data ? event.data : event.body);
    
const timeStamp = Date.now();
const HandleBars = require("handlebars");
const bucketForTemplates = {
  Bucket: templateBucket,
  Key: `${body.template}.hbs`,
};

const file = await s3.getObject(bucketForTemplates).promise();

const template = HandleBars.compile(file.Body.toString());
const renderedPage = template(body);

const page = await browser.newPage();

await page.setViewport({ deviceScaleFactor: 2 });
await page.setContent(renderedPage);

//wait for page to load
await page.waitForSelector("#image");
const image = await page.$("#image");

const box = await image.boundingBox();
const x = box["x"];
const y = box["y"];
const w = box["width"];
const h = box["height"];

const buffer = await page.screenshot({
  type: "jpeg",
  clip: { x: x, y: y, width: w, height: h },
});
    
await page.close();
await browser.close();
//save image to s3.

我正在拍摄的 div 设置的宽度为 760px,高度为 760px,但屏幕截图为 1520 X 1520。

如何将图片缩小到不那么大?

您使用 deviceScaleFactor: 2 视口设置启动 puppeteer:

const browser = await chromium.puppeteer.launch({
  defaultViewport: { width: 800, height: 600, deviceScaleFactor: 2 }, // <----
});

According to docs, it "can be thought of as DPR", or device pixel ratio,从而将分辨率放大2倍。

此设置的默认设置是 1,这就是您要用来获取正确尺寸的屏幕截图的设置。