Skip to content

Instantly share code, notes, and snippets.

@davidsharp
Last active July 19, 2019 11:25
Show Gist options
  • Select an option

  • Save davidsharp/cb2ab2c602feff23aea52693999bfc41 to your computer and use it in GitHub Desktop.

Select an option

Save davidsharp/cb2ab2c602feff23aea52693999bfc41 to your computer and use it in GitHub Desktop.
Quick PNG circle clipper
#!/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"));
});
});
@davidsharp

davidsharp commented Jun 2, 2017

Copy link
Copy Markdown
Author

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.

//linear-gradient(15deg, #44dd44, #dddd44);
  var g=ctx.createLinearGradient(img.width-10,0,0,img.height-10);
  g.addColorStop(0,"#dddd44");
  g.addColorStop(1,"#44dd44");
  ctx.fillStyle=g;
  ctx.fillRect(0, 0, img.width, img.height);

(The comment is what I was aiming for, but it's more approximate and just for reference)

@davidsharp

Copy link
Copy Markdown
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