Last active
October 4, 2019 14:44
-
-
Save davidsharp/a9bca57a83bad1037e349de0cadceb10 to your computer and use it in GitHub Desktop.
Tiles a png to an A4 landscape size – `node tilepng -p my/png/location/png-to-tile.png` (definitely works in Node 4.8.0)
This file contains hidden or 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
| #!/usr/bin/env node | |
| 'use strict'; | |
| // > npm i -g commander; npm i -g canvas; | |
| // this also requires Cairo: https://www.npmjs.com/package/canvas | |
| // > brew install pkg-config cairo libpng jpeg giflib | |
| const path = require('path'); | |
| const fs = require('fs'); | |
| const cmdr = require('commander'); | |
| const {createCanvas, Image} = require('canvas'); | |
| cmdr | |
| .option('-p, --path <n>', 'Path to the png to tile', (p)=>{return path.resolve(p)||undefined;}) | |
| .option('-s, --scale <n>', 'Value to scale source image by', (s)=>{return Number(s)||1;},1) | |
| .parse(process.argv); | |
| console.log('Manipulating : '+cmdr.path); | |
| console.log('Scaling : '+cmdr.scale); | |
| if(!cmdr.path){console.log('No --path given');process.exit();} | |
| fs.readFile(cmdr.path, (err, src) => { | |
| if (err) throw err; | |
| var img = new Image; | |
| img.src = src; | |
| var c={w:3508,h:2480} | |
| var canvas = createCanvas(c.w,c.h); | |
| var ctx = canvas.getContext('2d'); | |
| const iW = img.width*cmdr.scale | |
| const iH = img.height*cmdr.scale | |
| for(let w=1;w<(c.w+iW);w+=iW){for(let h=1;h<(c.h+iH);h+=iH){ | |
| ctx.drawImage(img, w, h, iW, iH); | |
| }} | |
| fs.writeFile(cmdr.path.replace(/(\.png|\.jpg)$/,".tiled.png"), canvas.toDataURL().replace(/^data:image\/png;base64,/, ""), 'base64', err => { | |
| if(err)console.log(err); | |
| else console.log('Complete! '+cmdr.path.replace(/(\.png|\.jpg)$/,".tiled.png")); | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment