Node gm - use crop and resize cause error

2019-08-08 15:49发布

问题:

The following code throw an error.

Error: Command failed: gm convert: geometry does not contain image (unable to crop image).

var gm = require('gm');

gm('/origin.jpg')
.resize(600)
.write('/beforeCrop', function (err) {
    // beforeCrop is 600 * 450
    gm('/beforeCrop')
    .crop(70, 70, 100, 100)
    .resize(50, 50)
    .write('/result', function (err) {
        if (err) throw err;
    });
});

Is seem that gm can not resolve the size of beforeCrop.

回答1:

Why not piping to a stream and reading from it on the fly?

var gm = require('gm');

gm('/origin.jpg')
.resize(600)
.stream(function (err,stdout,stderr) {
    // beforeCrop is 600 * 450
    gm(stdout) // gm can read buffers ;)
    .crop(70, 70, 100, 100)
    .resize(50, 50)
    .write('/result', function (err) {
        if (err) throw err;
    });
});

I'd also consider piping to another stream after cropping like so:

var gm = require('gm');

gm('/origin.jpg')
.resize(600)
.stream(function (err,stdout,stderr) {
    // beforeCrop is 600 * 450
    gm(stdout) // gm can read buffers ;)
    .crop(70, 70, 100, 100).stream(function (err,stdout,stderr) {
        gm(stdout).resize(50, 50)
        .write('/result', function (err) {
            if (err) throw err;
        });
    });
});

I had some problems when doing both on the same chain.



回答2:

You appear to be reading from and writing to your system's root directory. Unless you're running as root/administrator, you won't have the right permissions to do that, and if you are, you're probably (certainly if this is part of a Web server) opening up a gigantic security hole.