如何在node.js中使用graphicsmagick来裁剪圆形图片(其他方式可以通过其他方式在node.js上进行)

如何使用graphicsmagick裁剪圆形图片?

(使用png透明背景外圈)

我在node.js使用graphicsmagick,或者有任何其他方式使这在node.js

之前: http : //i.stack.imgur.com/B34C5.png

之后: http : //i.stack.imgur.com/PWjQW.png

经过许多小时的摆弄之后,我find了一个干净的解决scheme,使用node-gm和Imagemagick。

 var gm = require('gm').subClass({ imageMagick: true }); var original = 'app-server/photo.jpg'; var output = 'app-server/photo.png'; var size = 80; gm(original) .crop(233, 233,29,26) .resize(size, size) .write(output, function() { gm(size, size, 'none') .fill(output) .drawCircle(size/2,size/2, size/2, 0) .write(output, function(err) { console.log(err || 'done'); }); }); 

我使用另一个模块来解决这个问题:

这个代码是方形图像(this.height = this.width)

节点pngjs

 var fs = require('fs'), PNG = require('pngjs').PNG; fs.createReadStream(__dirname + "/input.png") .pipe(new PNG({ filterType: 4 })) .on('parsed', function() { for (var y = 0; y < this.height; y++) { for (var x = 0; x < this.width; x++) { var idx = (this.width * y + x) << 2; var radius = this.height / 2; if(y >= Math.sqrt(Math.pow(radius, 2) - Math.pow(x - radius, 2)) + radius || y <= -(Math.sqrt(Math.pow(radius, 2) - Math.pow(x - radius, 2))) + radius) { this.data[idx + 3] = 0; } } } this.pack().pipe(fs.createWriteStream(__dirname + "/output.png")); }); 

我可以用下面的插件来实现: https : //www.npmjs.com/package/circle-image

安装完成后:

 var images = require('circle-image'); var imageSizes = [125, 100, 30]; //uniqueId param is used to identify a user //so user the primary key or something guaranteed to be unique images.execute('imagepath', uniqueId, imageSizes).then(function (paths) { //array of circularized image paths console.log(paths[0]); //circle_user_{uniqueId}_150.png })