Last active
January 23, 2016 16:43
-
-
Save mattdesl/59214e0f0ee8b3ae614f to your computer and use it in GitHub Desktop.
devtool script to tile images into a single image
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
// install with: | |
// npm i -g devtool | |
// npm i img javascript-natural-sort electron-canvas-to-buffer | |
// | |
// run: | |
// devtool tile-folder.js -qch | |
var fs = require('fs') | |
var path = require('path') | |
var loadImage = require('img') | |
var natural = require('javascript-natural-sort') | |
var canvasToBuffer = require('electron-canvas-to-buffer') | |
// Your input/output settings | |
var folder = path.resolve(__dirname, 'tmp') | |
var output = path.resolve(__dirname, 'output') | |
var tileScale = 1 | |
var padding = 0 | |
var rows = 6 | |
var files = fs.readdirSync(folder).filter(function (x) { | |
return /\.(png|jpg|jpeg|gif|bmp|tiff)$/.test(x) | |
}).map(function (x) { | |
return 'tmp/' + x | |
}) | |
files.sort(natural) | |
var loadFiles = files.map(function (src) { | |
return new Promise(function (resolve, reject) { | |
loadImage(src, function (err, img) { | |
if (err) return reject(err) | |
resolve(img) | |
}) | |
}) | |
}) | |
Promise.all(loadFiles) | |
.then(render) | |
function render (images) { | |
var imageSize = [ | |
Math.floor(images[0].width * tileScale), | |
Math.floor(images[0].height * tileScale) | |
] | |
var canvas = document.createElement('canvas') | |
var ctx = canvas.getContext('2d') | |
var count = images.length | |
var cols = Math.ceil(count / rows) | |
canvas.width = imageSize[0] * cols + padding * (cols + 1) | |
canvas.height = imageSize[1] * rows + padding * (rows + 1) | |
images.forEach(function (img, i) { | |
var x = Math.floor(i % cols) | |
var y = Math.floor(i / cols) | |
ctx.drawImage(img, | |
padding + x * (padding + imageSize[0]), | |
padding + y * (padding + imageSize[1]), | |
imageSize[0], | |
imageSize[1]) | |
}) | |
var buffer = canvasToBuffer(canvas, 'image/png') | |
var outfile = path.resolve(output, 'image.png') | |
fs.writeFile(outfile, buffer, function (err) { | |
if (err) throw err | |
window.close() | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment