Last active
July 19, 2019 11:25
-
-
Save davidsharp/cb2ab2c602feff23aea52693999bfc41 to your computer and use it in GitHub Desktop.
Quick PNG circle clipper
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 | |
| const path = require('path'); | |
| const fs = require('fs'); | |
| const cmdr = require('commander'); | |
| //this requires Cairo: https://www.npmjs.com/package/canvas | |
| // brew install pkg-config cairo libpng jpeg giflib | |
| const {createCanvas, Image} = require('canvas'); | |
| cmdr | |
| .option('-p, --path <n>', 'Path to png to crop', (p)=>{return path.resolve(p)||undefined;}) | |
| .option('-m, --margin <n>', 'width of circle margin in pixels', (m)=>{return isNaN(parseInt(m))?undefined:parseInt(m);}) | |
| .parse(process.argv); | |
| console.log('Manipulating : '+cmdr.path); | |
| if(!cmdr.path){console.log('No --path given');process.exit();} | |
| fs.readFile(cmdr.path, function(err, src){ | |
| const margin = cmdr.margin||10; | |
| if (err) throw err; | |
| var img = new Image; | |
| img.src = src; | |
| var side = img.width>img.height?img.height:img.width | |
| var canvas = createCanvas(side+2, side+2); | |
| var ctx = canvas.getContext('2d'); | |
| //linear-gradient(15deg, #44dd44, #dddd44); | |
| /* | |
| var g=ctx.createLinearGradient(side-10,0,0,side-10); | |
| g.addColorStop(0,"#dddd44"); | |
| g.addColorStop(1,"#44dd44"); | |
| ctx.fillStyle=g; | |
| ctx.fillRect(0, 0, side, side); | |
| */ | |
| // Create a circle | |
| ctx.beginPath(); | |
| ctx.arc(side/2, side/2, (side/2)-margin, 0, Math.PI * 2, true); | |
| // Clip to the current path | |
| ctx.clip(); | |
| ctx.drawImage(img, (img.width-side)/2, (img.height-side)/2, side, side, 0, 0, side, side); | |
| fs.writeFile(cmdr.path.replace(/\.(jpg|png)$/,".clipped.png"), canvas.toDataURL().replace(/^data:image\/png;base64,/, ""), 'base64', function(err) { | |
| if(err)console.log(err); | |
| else console.log('Complete! '+cmdr.path.replace(/\.(jpg|png)$/,".clipped.png")); | |
| }); | |
| }); |
Author
Author
Newer version crops down non-square images, uses newer node-canvas version and doesn't overwrite .jpg files
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Throwing this in before the cropped image, gives a nice gradient.
I'll add it once I've thought about what command line options it should have.
(The comment is what I was aiming for, but it's more approximate and just for reference)