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' ) ;
64const { runInNativeContext} = require ( '../command-helpers/context-switcher' ) ;
75
86module . 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