Created
June 24, 2015 06:49
-
-
Save domenic/2d357fd9858708f4bd5a to your computer and use it in GitHub Desktop.
Image-flipping server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
const http = require("http"); | |
const url = require("url"); | |
const request = require("request"); | |
const jsdom = require("jsdom"); | |
const Canvas = require("canvas"); | |
http.createServer(function (req, res) { | |
console.log(req.url); | |
const pageUrl = url.parse(req.url, true).query["proxy-me"]; | |
if (!pageUrl) { | |
res.end(); | |
return; | |
} | |
jsdom.env(pageUrl, function (err, window) { | |
fixStylesheetUrls(window, pageUrl); | |
const images = window.document.querySelectorAll("img"); | |
Promise.all(Array.prototype.map.call(images, function (imgEl) { | |
return getImageContents(imgEl.src) | |
.then(rotateImage) | |
.then(function (rotatedCanvas) { | |
if (rotatedCanvas) { | |
imgEl.src = rotatedCanvas.toDataURL(); | |
} | |
}); | |
})) | |
.then(function () { | |
res.end(jsdom.serializeDocument(window.document)); | |
}) | |
.catch(function (err) { | |
res.end(err.stack); | |
}); | |
}); | |
}).listen(5002); | |
function fixStylesheetUrls(window, baseUrl) { | |
Array.prototype.forEach.call(window.document.querySelectorAll("link"), function (linkEl) { | |
linkEl.href = url.resolve(baseUrl, linkEl.href); | |
}); | |
} | |
function getImageContents(imgSrc) { | |
return new Promise(function (resolve, reject) { | |
request(imgSrc, { encoding: null }, function (error, response, buffer) { | |
if (error) { | |
reject(error); | |
} | |
resolve(buffer); | |
}); | |
}); | |
} | |
function rotateImage(imgBuffer) { | |
// Turn the image buffer into something the canvas can work with. | |
const img = new Canvas.Image(); | |
img.src = imgBuffer; | |
if (img.width === 0 || img.height === 0) { | |
// Image is invalid; bail out. | |
return; | |
} | |
// Create a canvas | |
const canvas = new Canvas(img.width, img.height); | |
const ctx = canvas.getContext("2d"); | |
// Do the funky translate-then-rotate-then-translate-back dance. | |
ctx.translate(img.width / 2, img.height / 2); | |
ctx.rotate(Math.PI); | |
ctx.translate(-img.width / 2, -img.height / 2); | |
// Draw the image onto our rotated canvas. | |
ctx.drawImage(img, 0, 0, img.width, img.height); | |
return canvas; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment