天天看點

nodejs裁剪圓形圖檔(crop to circle image)問題來源Solution參考

問題來源

在前端開發當中,經常有展示圓形圖像的需求。在H5開發當中,使用border-radius屬性就可以解決,安卓或者IOS,肯定也有相應辦法。

如果想在後端裁剪出圓形圖檔,該怎麼解決呢?

Solution

ImageMagic(未驗證)

如果系統使用的是imagemagic,可以使用如下指令裁剪:

convert -size x200 xc:none -fill walter.jpg -draw "circle 100,100 100,1" circle_thumb.png
           

對于于nodejs gm,代碼如下:

var gm = require('gm').subClass({ imageMagick: true });

var original = 'app-server/photo.jpg'; 
var output = 'app-server/photo.png';
var size = ;

gm(original)
  .crop(, ,,)
  .resize(size, size)
  .write(output, function() {

     gm(size, size, 'none')
        .fill(output)
        .drawCircle(size/,size/, size/, )
        .write(output, function(err) {
           console.log(err || 'done');
        });
  });
           

注意,該部分代碼來源于stackoverflow。由于部落客電腦上用的是GraphicsMagic,是以

上述指令未經驗證

node-pngjs

裁剪從原理上來說,就是讓處于

圓外的像素變成透明,即将其alpha通道改成0

。是以可以直接讀取并操作圖檔像素。

var fs = require('fs'),
PNG = require('pngjs').PNG;
var input = 'test.png';

fs.createReadStream(input)
    .pipe(new PNG({filterType: }))
    .on('parsed', function() {
        for (var y = ; y < this.height; y++) {
            for (var x = ; x < this.width; x++) {
                var idx = (this.width * y + x) << ;
                if (Math.pow(x-radius,) + Math.pow(y-radius,) > Math.pow(radius,)) {
                    this.data[idx+] = ; 
                }
            }
        }
        this.pack().pipe(fs.createWriteStream(input));
        callback(null, param);
    });
           

值得注意的是,

node-pngjs隻支援png圖檔的讀寫

,是以在裁剪之前需要先對圖檔進行格式轉化。這個辦法的優勢在于,

不依賴于圖形處理庫

,隻靠js代碼就可以搞定。

參考

How to use graphicsmagick in node.js to crop circle picture (other use any other way to make this on node.js)

node-pngjs

Crop or mask an image into a circle