Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support arbitrary cropping rectangles with im.crop(). #68

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Expand Up @@ -141,6 +141,8 @@ im.resize({
### crop(options, callback) ###
Convenience function for resizing and cropping an image. _crop_ uses the resize method, so _options_ and _callback_ are the same. _crop_ uses _options.srcPath_, so make sure you set it :) Using only _options.width_ or _options.height_ will create a square dimensioned image. Gravity can also be specified, it defaults to Center. Available gravity options are [NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast]

You can also specify the top and left coordinates of the crop rectangle within the image by specifying _top_ and _left_ in the options. These MUST be strings!! This is in accordance with ImageMagick's image geometric syntax. _top_ and _left_ each must begin with a _+_ or _-_ followed by an integer representing a pixel offset from the top-left of the original image.

Example:

```javascript
Expand All @@ -149,6 +151,8 @@ im.crop({
dstPath: 'cropped.jpg',
width: 800,
height: 600,
top: '+20',
left: '+30',
quality: 1,
gravity: "North"
}, function(err, stdout, stderr){
Expand Down
13 changes: 11 additions & 2 deletions imagemagick.js
Expand Up @@ -319,10 +319,17 @@ exports.crop = function (options, callback) {
dDst = t.opt.width / t.opt.height,
resizeTo = (dSrc < dDst) ? ''+t.opt.width+'x' : 'x'+t.opt.height,
dGravity = options.gravity ? options.gravity : "Center";

if(!t.opt.top && !t.opt.left) {
// Add -resize flag if this isn't an arbitrary crop rectangle.
args = args.concat(['-resize', resizeTo]);
} else {
// Since this is an arbitrary crop rectange, use -crop instead of -resize.
args = args.concat(['-crop', ''+t.opt.width + 'x' + t.opt.height + (t.opt.left ? t.opt.left : '+0') + (t.opt.top ? t.opt.top : '+0')]);
}

args = args.concat([
'-resize', resizeTo,
'-gravity', dGravity,
'-crop', ''+t.opt.width + 'x' + t.opt.height + '+0+0',
'+repage'
]);
ignoreArg = false;
Expand All @@ -346,6 +353,8 @@ exports.resizeArgs = function(options) {
colorspace: null,
width: 0,
height: 0,
top: 0,
left: 0,
strip: true,
filter: 'Lagrange',
sharpening: 0.2,
Expand Down