1. 程式人生 > >Node.js 影象處理

Node.js 影象處理

1、下載影象

var request = require('request');
var fs = require('fs');
var images = require("images");
PNG = require('pngjs').PNG;

function savedImage(url, filename) {
        request(url).pipe(fs.createWriteStream(filename));
}

var url1 = "https://6c62-lbs-f8c394-1252842602.tcb.qcloud.la/my-image.png?sign=9faa85374df48eeead00fdf8da944c4c&t=1540044672"
var file1 = "./file1.png"
savedImage(url1, file1);

var url2 = "https://6c62-lbs-f8c394-1252842602.tcb.qcloud.la/location.png?sign=3b11636452eada2921d5ba55c769137c&t=1540045035"
var file2 = "./file2.png"
savedImage(url2, file2);

2、影象圓裁剪

var request = require('request');
var fs = require('fs');
var images = require("images");
PNG = require('pngjs').PNG;

var input = "file1.png"
var radius = 20

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

3、合併圖

var request = require('request');
var fs = require('fs');
var images = require("images");

var file1 = "./file1.png"
var file2 = "./file2.png"
//var image1 = images(file2)
var image1 = images(file2)
var image2 = images(file1)

var height2 = image2.height()
var width2 = image2.width()
var c = width2
if (c > height2) {
        c = height2
}
var image3 = images(image2,0,0,c,c)
image3.save("file1_1.png")

image1.size(25, 48);
image3.resize(20, 20);
image3.save("file1_2.png")
image1.draw(image3, 2, 2).save("output.png", {quality:100});