Oliver Moran Oliver Moran - 1 year ago 124
Node.js Question

Pure JavaScript image manipulation

I have a use case where I want to created (a) a Node application that (b) performs basic image manipulations (PNG resize and crop) but (c) where I cannot have external dependencies like native libraries, GraphicsMagick, ImageMagick, PhantonJS, Inkscape, etc.

It all has to be done in pure JavaScript.

Given how simple the manipulation I want to do is (just PNG resize and crop) this doesn't seem impossible. However, I cannot find a crop/resize library that doesn't ultimately have an external or native dependency.

Does such a genuinely pure JavaScript library exist for crop/resize? How difficult would it be to implement this in pure JavaScript, if I had to do it myself? And where should I start?

Alternatively, is there a suitable C function for this that I could compile using emscripten, for example?

Answer Source

OK, I ended up rolling my own, which I have released as a NPM package here: https://www.npmjs.org/package/jimp

Example usage is:

var Jimp = require("jimp");

var lenna = new Jimp("lenna.png", function () {
    this.crop(100, 100, 300, 200) // crop
        .resize(220, 220) // resize
        .write("lenna-small-cropped.png"); // save

The breakthrough was finding a JavaScript bicubic two-pass scaling algorithm here: https://github.com/grantgalitz/JS-Image-Resizer

Kudos to Mike 'Pomax' Kamermans for pointing the right direction to take and to Grant Galitz for an amazing scaling algorithm.