nodejs将图像拆分成块

时间:2016-08-12 21:41:10

标签: node.js image split

是否有nodeJS方式将图像拆分为单个块? 可能有不同的尺寸?

喜欢下图中的照片

This is an example wat i will do

1 个答案:

答案 0 :(得分:1)

我使用jimp完成了类似的操作,但它可能更简洁......

var Jimp = require("jimp");

/**
 * @param filename - input file
 * @param numSlices - how many slices
 * @param attenuation - how quickly slices get smaller
 */
function sliceImage(filename, numSlices, attenuation) {
    Jimp.read(filename).then(image => {
        let w = image.bitmap.width;
        let h = image.bitmap.height;
        let sliceWidth = w / numSlices;
        let midlane = w / 2;
        let slack = 0.001;

        let slices = [];

        function slicePair(left, right) {
            if (left < (0 - slack) || (right - sliceWidth) > (w + slack)) {
                return;
            }

            let leftSlice = image.clone();
            let rightSlice = image.clone();

            leftSlice.crop(left, 0, sliceWidth, h);
            rightSlice.crop(right - sliceWidth, 0, sliceWidth, h);

            slices.push(leftSlice);
            slices.push(rightSlice);

            slicePair(left - sliceWidth, right + sliceWidth);
        }

        function doSlice() {
            if (numSlices % 2 == 0) {
                slicePair(midlane - sliceWidth, midlane + sliceWidth);
            } else {
                let middle = image.clone();
                middle.crop(midlane - (sliceWidth / 2), 0, sliceWidth, h);
                slices.push(middle);
                slicePair(midlane - (1.5 * sliceWidth), midlane + (1.5 * sliceWidth));
            }
        }

        function overlay() {
            let canvas = image.clone().brightness(1);
            let odd = !(slices.length % 2 === 0);
            let adjust = odd ? (sliceWidth / 2) : 0;
            slices.reverse();
            if (odd) {
                let middle = slices.pop();
                canvas.composite(middle, (midlane - (sliceWidth / 2)), 0);
            }
            for (let i = 0; i < (slices.length + 2); i++) {
                let k = odd ? (i + 1) : i;
                let left = slices.pop().crop(0, attenuation * k, sliceWidth, (h - (attenuation * k) * 2));
                let right = slices.pop().crop(0, attenuation * k, sliceWidth, (h - (attenuation * k) * 2));
                canvas.composite(left, (midlane - ((i + 1) * sliceWidth)) - adjust, (attenuation * k));
                canvas.composite(right, (midlane + (i * sliceWidth)) + adjust, (attenuation * k));
            }
            canvas.write("result.jpg");
            return canvas;
        }

        doSlice();
        return overlay();
    });
}