Is there a way in node gm(graphic magic) crop by shape?

Question!

I'm trying to crop picture by a shape picture and tried this

let imageDoc = gm(filePath).resize(100, 100);

imageDoc.mask(`${shapesPath}/hexagon.svg`);

It acts like nothing was done but resizes correctly. Also tried using png file instead of svg, but there is no result at all, maybe there is some way to debug it, or I'm doing something wrong?

By : Shekspir


Answers

According to user Pirijan:

Mask doesn't do anything on it's own, it's pretty useless really. It merely takes the supplied mask image and uses it to write protect the masked pixels from subsequent alteration if additional processing / drawing is performed on the image.

So it seems that .mask() it only useful when used together with another command.

The documentation for GraphicsMagick can be quite confusing, and I'm sure there are multiple ways of masking an image. Here's how I do it:

function mask(img, mask){
    gm()
    .command("composite")
    .compose("CopyOpacity")
    .in(img, mask, "-matte")
    .write(img, function(err){
        if(err){
            console.log(err)
        } else {
            console.log("Success! Image " + img + " was masked with mask " + mask);
        }
    });
}

However, this doesn't use the alpha channel from mask, instead it works with a black and white mask with no alpha channel. It also requires both img and mask to have identical dimensions.

It works by copying the value of each pixel in mask to the alpha channel of img. The -matte option tells gm to create an alpha channel on img if it doesn't already have one.

Since node-gm uses the debug library from visionmedia you can turn on debug output to the console by setting the environment variable DEBUG=gm, like so (in Unix/OS X):

DEBUG=gm node index.js

This will print the exact commands that node-gm invokes.

By : karklud


This video can help you solving your question :)
By: admin