Jimp: Low level manipulation

Created on 15 Sep 2016  路  3Comments  路  Source: oliver-moran/jimp

hi, i use autocrop and i nedd give to the image a border margin.
Any suggestion?

Most helpful comment

You would have to create new image of desired size and put result what's left after autocrop() in the middle of it to get extra padding.

Here, I wrote it for you

function autocropWithMargin(image, margin) {
    var backgroundColor = image.bitmap.data.readUInt32BE(0);
    var originalWidth = image.bitmap.width;
    var originalHeight = image.bitmap.height;

    // image = image.clone(); // uncomment this if you don't want original image to be modified
    image.autocrop();

    if (image.bitmap.width === originalWidth && image.bitmap.height === originalHeight) {
        return image;
    }

    var canvas = new Jimp(image.bitmap.width + margin * 2, image.bitmap.height + margin * 2, backgroundColor);

    // clear the area for the image
    canvas.scan(margin, margin, image.bitmap.width, image.bitmap.height, function(x, y, idx) {
        canvas.bitmap.data[idx + 3] = 0;
    });

    canvas.composite(image, margin, margin);
    return canvas;
}

// Usage

Jimp.read('your-image.png', function(err, image) {
    if (err) throw err;

    image = autocropWithMargin(image, 10);
    image.write('cropped-with-margin-or-same-as-original.png');
});

All 3 comments

You would have to create new image of desired size and put result what's left after autocrop() in the middle of it to get extra padding.

Here, I wrote it for you

function autocropWithMargin(image, margin) {
    var backgroundColor = image.bitmap.data.readUInt32BE(0);
    var originalWidth = image.bitmap.width;
    var originalHeight = image.bitmap.height;

    // image = image.clone(); // uncomment this if you don't want original image to be modified
    image.autocrop();

    if (image.bitmap.width === originalWidth && image.bitmap.height === originalHeight) {
        return image;
    }

    var canvas = new Jimp(image.bitmap.width + margin * 2, image.bitmap.height + margin * 2, backgroundColor);

    // clear the area for the image
    canvas.scan(margin, margin, image.bitmap.width, image.bitmap.height, function(x, y, idx) {
        canvas.bitmap.data[idx + 3] = 0;
    });

    canvas.composite(image, margin, margin);
    return canvas;
}

// Usage

Jimp.read('your-image.png', function(err, image) {
    if (err) throw err;

    image = autocropWithMargin(image, 10);
    image.write('cropped-with-margin-or-same-as-original.png');
});

Great, I took a similar manner to solve it.
Thanks!

You should probably close the issue

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kolbma picture kolbma  路  6Comments

jBernavaPrah picture jBernavaPrah  路  4Comments

Inbarasan16 picture Inbarasan16  路  3Comments

haydenbleasel picture haydenbleasel  路  6Comments

slidenerd picture slidenerd  路  4Comments