Skip to content

Commit 8e8c389

Browse files
committed
perf: switch from pngjs to sharp
1 parent aa087c9 commit 8e8c389

File tree

4 files changed

+7830
-144
lines changed

4 files changed

+7830
-144
lines changed

lib/commands/screenshot.js

+9-29
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
'use strict';
22

3-
const {PNG} = require('pngjs');
4-
const concat = require('concat-stream');
5-
const streamifier = require('streamifier');
3+
const sharp = require('sharp');
64
const {runInNativeContext} = require('../command-helpers/context-switcher');
75

86
module.exports = (browser, {elementUtils}) => {
@@ -12,31 +10,13 @@ module.exports = (browser, {elementUtils}) => {
1210
const cropCoords = await runInNativeContext(browser, {fn: elementUtils.calcWebViewCoords.bind(elementUtils), args: [browser, {bodyWidth, pixelRatio}]});
1311
const screenshotResult = await baseScreenshotFn();
1412

15-
return new Promise((resolve, reject) => {
16-
const handleError = (msg) => (err) => reject(`Error occured while ${msg}: ${err.message}`);
17-
18-
streamifier.createReadStream(Buffer.from(screenshotResult, 'base64'))
19-
.on('error', handleError('converting buffer to readable stream'))
20-
.pipe(new PNG())
21-
.on('error', handleError('writing buffer to png data'))
22-
.on('parsed', function() {
23-
const destination = new PNG({width: cropCoords.width, height: cropCoords.height});
24-
25-
try {
26-
this.bitblt(destination, cropCoords.left, cropCoords.top, cropCoords.width, cropCoords.height);
27-
} catch (err) {
28-
reject(`Error occured while copying pixels from source to destination png: ${err.message}`);
29-
}
30-
31-
destination.pack()
32-
.on('error', handleError('packing png data to buffer'))
33-
.pipe(concat((buffer) => {
34-
const strBase64 = buffer.toString('base64');
35-
36-
resolve(strBase64);
37-
}))
38-
.on('error', handleError('concatenating png data to a single buffer'));
39-
});
40-
});
13+
try {
14+
return await sharp(Buffer.from(screenshotResult, 'base64'))
15+
.extract(cropCoords)
16+
.toBuffer()
17+
.then(buf => buf.toString('base64'));
18+
} catch (e) {
19+
throw new Error(`Failed to take screenshot: ${e}`);
20+
}
4121
});
4222
};

0 commit comments

Comments
 (0)