2

I've been trying to use node-gm + Imagemagick to circular crop an image.

Anyways, here's my attempt at creating a mask using a black circle.

var original = 'app-server/photo.jpg'; 
var output = 'app-server/photo.png';
var maskPath = 'app-server/photo-mask.png';

gm(original)
     .crop(233, 233,29,26)
     .resize(80, 80)
     .setFormat('png')
     .write(output, function (err) {
        console.log(err || 'cropped to target size');

        gm(output)
           .out('-size', '80x80')
           .background('black')
           .drawCircle(20,20, 0, 0)
           .toBuffer('PNG',function (err, buffer) {

              console.log(err || 'created circular black mask');

              //docs say "a buffer can be passed instead of 
              //a filepath" but this is apparently false
              //and say something unclear about using black/white colors for masking.
              //I'm clearly lost
              gm(output)
                 .mask(maskPath)
                 .write(output,  function (err) {
                    console.log(err || 'applied circular black mask to image');
                 });
           });

     });

I'm sure this can be done via some fancy string command concatenation, but despite my lack of image processing prowess, I still want to keep the code clean. I'm really looking for a solution using node-gm functions, preferably with less operations than my attempt (also preferably something that works, unlike mine).

I also tried to chain out the function calls for this command with no success: https://stackoverflow.com/a/999563/1267778

Note I need to crop at a specific location (w,h,x,y) so these solutions also don't work for me:

node-pngjs

node-circle-image

Community
  • 1
  • 1
parliament
  • 21,544
  • 38
  • 148
  • 238

1 Answers1

1

Got it! After many hours of fiddling, I got exactly what I needed.

gm(originalFilePath)
  .crop(233, 233,29,26)
  .resize(size, size)
  .write(outputFilePath, function(err) {
     gm(size, size, 'none')
        .fill(outputFilePath)
        .drawCircle(size/2,size/2, size/2, 0)
        .write(output, function(err) {
           console.log(err || 'done');
        });
  });

I'm using JCrop to allow the user to crop the image on the front-end and pass the coordinates (w,h,x,y) into crop().

parliament
  • 21,544
  • 38
  • 148
  • 238
  • Hi, can you help understanding from line 5 = > "gm (size , size , 'none') " ? please ? – Neer Patel May 20 '18 at 20:41
  • I am getting some error like , "gm convert : unrecognized color" . and I don't know which one of this function calls passes color name . – Neer Patel May 20 '18 at 20:43