本地化的nodeJS调整缓冲区图像大小

6

我在NODEjs中有一个以缓冲区形式存在的图像,并且我想要调整它的大小。

从理论上讲,这应该可以在nodeJS中完成,因为我可以访问缓冲区,其中包含所有像素数据。

我已经查找了很多地方,想要使用本地(仅限!)nodejs而没有外部库来简单地调整图像大小,但是我只找到了使用库的解决方案:

https://www.npmjs.com/package/gm

Node gm-调整图像大小并保持纵横比?

Node.js:无需ImageMagick进行图像调整大小 Node.js中调整图像大小的简单方法?

如何在Node.js中调整图像大小?

如何在Node js中调整图像大小

Node.js调整图像大小

在Node js中调整图像大小

在nodejs中下载图片并调整大小

使用Nodejs和Imagemagick调整图像大小

Nodejs通过保持纵横比将图像调整为精确大小

如何在node.js上调整图像大小

在NodeJS&gm中调整和裁剪图像并保持纵横比

如何使用multer在nodejs中调整图像大小

尝试使用sharp Node.js调整流图像大小

Node.js: 不使用ImageMagick调整图像大小

使用gm在nodejs中调整图像大小而无需上传

使用jimp在Node.js中调整图像大小并获取新图像的路径

但是所有这些解决方案都使用了某种库,但我想只使用纯NodeJS。

我可以使用Buffer读取像素,因此应该能够编写一个调整大小的Buffer,就像C ++线程http://www.cplusplus.com/forum/general/2615/和许多其他线程一样,简单地循环遍历像素并将其调整大小。

我找到了这个问题在HTML5画布中调整图像大小,它使用纯客户端JavaScript实现了图像调整大小,并且并不依赖于canvas drawImage来调整大小(只需要获取图像数据),下面是他所使用的代码:

function lanczosCreate(lobes) {
    return function(x) {
        if (x > lobes)
            return 0;
        x *= Math.PI;
        if (Math.abs(x) < 1e-16)
            return 1;
        var xx = x / lobes;
        return Math.sin(x) * Math.sin(xx) / x / xx;
    };
}

// elem: canvas element, img: image element, sx: scaled width, lobes: kernel radius
function thumbnailer(elem, img, sx, lobes) {
    this.canvas = elem;
    elem.width = img.width;
    elem.height = img.height;
    elem.style.display = "none";
    this.ctx = elem.getContext("2d");
    this.ctx.drawImage(img, 0, 0);
    this.img = img;
    this.src = this.ctx.getImageData(0, 0, img.width, img.height);
    this.dest = {
        width : sx,
        height : Math.round(img.height * sx / img.width),
    };
    this.dest.data = new Array(this.dest.width * this.dest.height * 3);
    this.lanczos = lanczosCreate(lobes);
    this.ratio = img.width / sx;
    this.rcp_ratio = 2 / this.ratio;
    this.range2 = Math.ceil(this.ratio * lobes / 2);
    this.cacheLanc = {};
    this.center = {};
    this.icenter = {};
    setTimeout(this.process1, 0, this, 0);
}

thumbnailer.prototype.process1 = function(self, u) {
    self.center.x = (u + 0.5) * self.ratio;
    self.icenter.x = Math.floor(self.center.x);
    for (var v = 0; v < self.dest.height; v++) {
        self.center.y = (v + 0.5) * self.ratio;
        self.icenter.y = Math.floor(self.center.y);
        var a, r, g, b;
        a = r = g = b = 0;
        for (var i = self.icenter.x - self.range2; i <= self.icenter.x + self.range2; i++) {
            if (i < 0 || i >= self.src.width)
                continue;
            var f_x = Math.floor(1000 * Math.abs(i - self.center.x));
            if (!self.cacheLanc[f_x])
                self.cacheLanc[f_x] = {};
            for (var j = self.icenter.y - self.range2; j <= self.icenter.y + self.range2; j++) {
                if (j < 0 || j >= self.src.height)
                    continue;
                var f_y = Math.floor(1000 * Math.abs(j - self.center.y));
                if (self.cacheLanc[f_x][f_y] == undefined)
                    self.cacheLanc[f_x][f_y] = self.lanczos(Math.sqrt(Math.pow(f_x * self.rcp_ratio, 2)
                            + Math.pow(f_y * self.rcp_ratio, 2)) / 1000);
                weight = self.cacheLanc[f_x][f_y];
                if (weight > 0) {
                    var idx = (j * self.src.width + i) * 4;
                    a += weight;
                    r += weight * self.src.data[idx];
                    g += weight * self.src.data[idx + 1];
                    b += weight * self.src.data[idx + 2];
                }
            }
        }
        var idx = (v * self.dest.width + u) * 3;
        self.dest.data[idx] = r / a;
        self.dest.data[idx + 1] = g / a;
        self.dest.data[idx + 2] = b / a;
    }

    if (++u < self.dest.width)
        setTimeout(self.process1, 0, self, u);
    else
        setTimeout(self.process2, 0, self);
};
thumbnailer.prototype.process2 = function(self) {
    self.canvas.width = self.dest.width;
    self.canvas.height = self.dest.height;
    self.ctx.drawImage(self.img, 0, 0, self.dest.width, self.dest.height);
    self.src = self.ctx.getImageData(0, 0, self.dest.width, self.dest.height);
    var idx, idx2;
    for (var i = 0; i < self.dest.width; i++) {
        for (var j = 0; j < self.dest.height; j++) {
            idx = (j * self.dest.width + i) * 3;
            idx2 = (j * self.dest.width + i) * 4;
            self.src.data[idx2] = self.dest.data[idx];
            self.src.data[idx2 + 1] = self.dest.data[idx + 1];
            self.src.data[idx2 + 2] = self.dest.data[idx + 2];
        }
    }
    self.ctx.putImageData(self.src, 0, 0);
    self.canvas.style.display = "block";
};

接下来是一张图片(用var img = new Image(); img.src = "something"创建):

img.onload = function() {
    var canvas = document.createElement("canvas");
    new thumbnailer(canvas, img, 188, 3); //this produces lanczos3
    // but feel free to raise it up to 8. Your client will appreciate
    // that the program makes full use of his machine.
    document.body.appendChild(canvas);
};

首先,客户端的速度非常慢,但是服务器上的速度可能会更快。在Node.js中需要替换或不存在的内容包括ctx.getImageData(可能可以用缓冲区来复制)

有人知道从哪里开始在Node.js中处理此问题吗?这在性能方面是否实用?如果不行,是否可以使用纯Node-gyp来提高性能,使用上述C++教程中的代码?(以下是该教程的代码)

#include<iostream>

class RawBitMap
{
public:
    RawBitMap():_data(NULL), _width(0),_height(0)
    {};

    bool Initialise()
    {
        // Set a basic 2 by 2 bitmap for testing.
        //
        if(_data != NULL)
            delete[] _data;

        _width = 2;
        _height = 2;    
        _data = new unsigned char[ GetByteCount() ];

        //
        _data[0] = 0;   // Pixels(0,0) red value
        _data[1] = 1;   // Pixels(0,0) green value
        _data[2] = 2;   // Pixels(0,0) blue value
        _data[3] = 253; // Pixels(1,0)
        _data[4] = 254;
        _data[5] = 255;
        _data[6] = 253; // Pixels(0,1)
        _data[7] = 254;
        _data[8] = 255;
        _data[9] = 0;   // Pixels(1,1)
        _data[10] = 1;
        _data[11] = 2;  

        return true;
    }

    // Perform a basic 'pixel' enlarging resample.
    bool Resample(int newWidth, int newHeight)
    {
        if(_data == NULL) return false;
        //
        // Get a new buuffer to interpolate into
        unsigned char* newData = new unsigned char [newWidth * newHeight * 3];

        double scaleWidth =  (double)newWidth / (double)_width;
        double scaleHeight = (double)newHeight / (double)_height;

        for(int cy = 0; cy < newHeight; cy++)
        {
            for(int cx = 0; cx < newWidth; cx++)
            {
                int pixel = (cy * (newWidth *3)) + (cx*3);
                int nearestMatch =  (((int)(cy / scaleHeight) * (_width *3)) + ((int)(cx / scaleWidth) *3) );

                newData[pixel    ] =  _data[nearestMatch    ];
                newData[pixel + 1] =  _data[nearestMatch + 1];
                newData[pixel + 2] =  _data[nearestMatch + 2];
            }
        }

        //
        delete[] _data;
        _data = newData;
        _width = newWidth;
        _height = newHeight; 

        return true;
    }

    // Show the values of the Bitmap for demo.
    void ShowData()
    {
        std::cout << "Bitmap data:" << std::endl;
        std::cout << "============" << std::endl;
        std::cout << "Width:  " << _width  << std::endl;
        std::cout << "Height: " << _height  << std::endl;
        std::cout << "Data:" << std::endl;

        for(int cy = 0; cy < _height; cy++)
        {
            for(int cx = 0; cx < _width; cx++)
            {
                int pixel = (cy * (_width *3)) + (cx*3);
                std::cout << "rgb(" << (int)_data[pixel] << "," << (int)_data[pixel+1] << "," << (int)_data[pixel+2] << ") ";
            }
            std::cout << std::endl;
        }
        std::cout << "_________________________________________________________" << std::endl;
    }


    // Return the total number of bytes in the Bitmap.
    inline int GetByteCount()
    {
        return (_width * _height * 3);
    }

private:
    int _width;
    int _height;
    unsigned char* _data;

};


int main(int argc, char* argv[])
{
    RawBitMap bitMap;

    bitMap.Initialise();
    bitMap.ShowData();

    if (!bitMap.Resample(4,4))
        std::cout << "Failed to resample bitMap:" << std::endl ; 
    bitMap.ShowData();

    bitMap.Initialise();
    if (!bitMap.Resample(3,3))
        std::cout << "Failed to resample bitMap:" << std::endl ;
    bitMap.ShowData();


    return 0;
}

我猜这是创建一个2x2的位图并对其进行调整大小,但基本原则仍然可以应用于纯node-gyp中。有其他人做过这个吗?这是否实用?


1
你看过jimp了吗?https://github.com/oliver-moran/jimp 它是一个纯JavaScript图像处理库,包括高质量的调整大小功能。当然,它比本地解决方案慢得多,可能会慢40倍,参见https://sharp.pixelplumbing.com/performance,但当选择库时性能并不是唯一的因素。 - jcupitt
@jcupitt 哦,太棒了,我在其他答案中找到了jimp,但立刻就排除了它,没有意识到它完全是用JavaScript编写的。谢谢你指出。 - B''H Bi'ezras -- Boruch Hashem
1个回答

3

发现一种仅使用Node的pngjs库(纯本地写成,因此甚至可以进行优化)和内置流库的简单快速方法。所以在你的代码顶部只需执行var PNG = require("pngjs").PNG, stream = require("stream");,然后使用以下代码:

function cobRes(iBuf, width, cb) {
        b2s(iBuf)
        .pipe(new PNG({
            filterType: -1
        }))
        .on('parsed', function() {

            var nw = width;
            var nh = nw *  this.height /this.width;
            var f = resize(this, nw, nh);

            sbuff(f.pack(), b=>{
                cb(b);
            })
        })


        function resize(srcPng, width, height) {
            var rez = new PNG({
                width:width,
                height:height
            });
            for(var i = 0; i < width; i++) {
                var tx = i / width,
                    ssx = Math.floor(tx * srcPng.width);
                for(var j = 0; j < height; j++) {
                    var ty = j / height,
                        ssy = Math.floor(ty * srcPng.height);
                    var indexO = (ssx + srcPng.width * ssy) * 4,
                        indexC = (i + width * j) * 4,
                        rgbaO = [
                            srcPng.data[indexO  ],
                            srcPng.data[indexO+1],
                            srcPng.data[indexO+2],
                            srcPng.data[indexO+3]
                        ]
                    rez.data[indexC  ] = rgbaO[0];
                    rez.data[indexC+1] = rgbaO[1];
                    rez.data[indexC+2] = rgbaO[2];
                    rez.data[indexC+3] = rgbaO[3];
                }
            }
            return rez;
        }

        function b2s(b) {
            var str = new stream.Readable();
            str.push(b);
            str.push(null);
            return str;
        }
        function sbuff(stream, cb) {
            var bufs = []
            var pk = stream;
            pk.on('data', (d)=> {
                bufs.push(d);

            })
            pk.on('end', () => {
                var buff = Buffer.concat(bufs);
                cb(buff);
            });
        }
    }

然后使用:
cobRes(fs.readFileSync("somePNGfile.png"), 200, buffer => fs.writeFileSync("new.png", buffer))

不确定为什么每个人都在使用复杂的库来完成这个:)


1
这很简单易懂,但是由于你正在进行最近邻插值,它将会很慢且质量不佳。边缘会出现难看的锯齿状,重复图案上会出现讨厌的莫尔纹效应。https://dev59.com/m2oy5IYBdhLWcg3wUcb_#57678066有一个测试图像以及样本,展示了你可能会遇到的各种伪影。 - jcupitt
@jcupitt 很有趣,你有没有使用纯JS的替代方案? - B''H Bi'ezras -- Boruch Hashem
你好,是的,jimp有高质量的调整大小操作,例如:https://github.com/oliver-moran/jimp/blob/master/packages/plugin-resize/src/modules/resize2.js#L252。不过它会比等效质量的本地调整大小慢40倍左右。 - jcupitt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接