crop: Permit specifying the gravity as a string.

Will be looked up in require('sharp').gravity.
This commit is contained in:
Andreas Lind 2015-08-19 14:49:00 +02:00
parent c4a278ec9c
commit faa515d969
2 changed files with 20 additions and 1 deletions

View File

@ -143,6 +143,8 @@ Sharp.prototype.crop = function(gravity) {
this.options.canvas = 'crop'; this.options.canvas = 'crop';
if (typeof gravity === 'number' && !Number.isNaN(gravity) && gravity >= 0 && gravity <= 4) { if (typeof gravity === 'number' && !Number.isNaN(gravity) && gravity >= 0 && gravity <= 4) {
this.options.gravity = gravity; this.options.gravity = gravity;
} else if (typeof gravity === 'string' && typeof module.exports.gravity[gravity] === 'number') {
this.options.gravity = module.exports.gravity[gravity];
} else { } else {
throw new Error('Unsupported crop gravity ' + gravity); throw new Error('Unsupported crop gravity ' + gravity);
} }

View File

@ -81,10 +81,27 @@ describe('Crop gravities', function() {
}); });
}); });
it('Invalid', function() { it('allows specifying the gravity as a string', function(done) {
sharp(fixtures.inputJpg)
.resize(80, 320)
.crop('east')
.toBuffer(function(err, data, info) {
if (err) throw err;
assert.strictEqual(80, info.width);
assert.strictEqual(320, info.height);
fixtures.assertSimilar(fixtures.expected('gravity-east.jpg'), data, done);
});
});
it('Invalid number', function() {
assert.throws(function() { assert.throws(function() {
sharp(fixtures.inputJpg).crop(5); sharp(fixtures.inputJpg).crop(5);
}); });
}); });
it('Invalid string', function() {
assert.throws(function() {
sharp(fixtures.inputJpg).crop('yadda');
});
});
}); });