Browse Source

Add a white background to screenshots

Gaël Métais 10 years ago
parent
commit
3f27ae249a
1 changed files with 35 additions and 0 deletions
  1. 35 0
      lib/screenshotHandler.js

+ 35 - 0
lib/screenshotHandler.js

@@ -48,6 +48,8 @@ var screenshotHandler = function() {
 
             })
 
+            .then(this.addWhiteBackground)
+
             .then(this.toBuffer);
     };
 
@@ -92,6 +94,39 @@ var screenshotHandler = function() {
         return deferred.promise;        
     };
 
+    // If the page doesn't set a background color, the default PhantomJS one is transparent.
+    // When transforming PNG to JPG, transparent pixels become black.
+    // This is why we need to had a transparent background.
+    this.addWhiteBackground = function(image) {
+        var deferred = Q.defer();
+
+        // Create a canvas with the same dimensions as your image:
+        lwip.create(image.width(), image.height(), 'white', function(err, canvas){
+            if (err) {
+                debug('Could not create a white canvas');
+                debug(err);
+
+                deferred.reject(err);
+            } else {
+                // Paste original image on top of the canvas
+                canvas.paste(0, 0, image, function(err, image){
+                    if (err) {
+                        debug('Could not paste image on the white canvas');
+                        debug(err);
+
+                        deferred.reject(err);
+                    } else {
+                        // Now image has a white background...
+                        debug('White background correctly added');
+                        deferred.resolve(image);
+                    }
+                });
+            }
+        });
+
+        return deferred.promise;
+    };
+
 
     this.toBuffer = function(image) {
         var deferred = Q.defer();