Search code examples
meteorimagemagickgraphicsmagick

Read image from base64 string in Meteor using imagemagick


I'm using cfs:graphicsmagick package for meteor and I want to read image from base64 string.

Meteor.methods({
  "readImage"(imgSrc) {
    const imageMagick = gm.subClass({ imageMagick: true });

    imageMagick(imgSrc)
    .write("path/to/image.jpg", (err) => {
      if (err) console.log(err);
      else console.log("yay!")
    });
  }
});

However when I try to run this code I get an error:

{ [Error: spawn ENAMETOOLONG] code: 'ENAMETOOLONG', errno: 'ENAMETOOLONG', syscall: 'spawn' }

I tried converting string to buffer via new Buffer(string, [encoding]) but no luck.

The string is similar to this: data:image/png;base64,iVBORw0K....

Any suggestions on how can I make it work?


Solution

  • Try to pass the base64 string without type definition (data:image/png;base64,) up until the comma symbol. Eg: iVBORw0K...

    I'm using this function to do the conversion:

    var fs = Npm.require('fs');
    ...
    base64_decode: function(base64str, file) {
        var bitmap = new Buffer(base64str, 'base64');
        fs.writeFileSync(file, bitmap);
    }
    

    sample usage:

    base64_decode('iVBORw0K...', '/path/to/file.png');