Closed sindresorhus closed 7 years ago
Yup, I thought of this as well. Haven't found any good module (without native dependencies) besides https://github.com/oliver-moran/jimp that supports image resizing though.
Still requires https://github.com/Automattic/node-canvas which is a pain to install.
I also like this idea.
What about using a headless browser with Canvas?
A headless browser would make for a hassle-free dependency.
You could use (or pull inspiration from) processing.js' resize function:
resize: function(w, h) {
if (this.isRemote) { // Remote images cannot access imageData
throw "Image is loaded remotely. Cannot resize.";
}
if (this.width !== 0 || this.height !== 0) {
// make aspect ratio if w or h is 0
if (w === 0 && h !== 0) {
w = Math.floor(this.width / this.height * h);
} else if (h === 0 && w !== 0) {
h = Math.floor(this.height / this.width * w);
}
// put 'this.imageData' into a new canvas
var canvas = getCanvasData(this.imageData).canvas;
// pull imageData object out of canvas into ImageData object
var imageData = getCanvasData(canvas, w, h).context.getImageData(0, 0, w, h);
// set this as new pimage
this.fromImageData(imageData);
}
}
Once you are in the browser, resizing the image can be done in pure JavaScript.
What about using a headless browser with Canvas?
That's way too slow for my use-case. And PhantomJS is huge.
Ah, I see.
What about lwip? I have used it in the past, on a similar module (my module would output variably-sized mobile app icons from a single image source) and it worked it really well for me at the time.
lwip was a super-easy install via npm.
lwip seems pretty similar to jimp. I wonder how fast it is though.
lwip readme:
Note: Installation of this module involves compiling native code. If npm install lwip failes, you probably need to setup your system. See instructions. Building on Windows with Visual Studio requires version 2013 or higher.
That is a nightmare for Windows users.
Yeah, I'm just going to go with jimp. It has no native dependencies and it has https://github.com/oliver-moran/jimp/blob/master/resize.js.
Ah. Windows users. Yeah, lwip was incredibly painless to install on a Mac.
Looks like it's jimp, for the win!
https://github.com/kevva/resize-img. Just need to add some logic in here and for which sizes that should be generated etc.
I don't want to manually create all the sizes. Let me specify a large image and have it handle generating the different sizes for me.
Example, I want to be able to just specify something like this file: https://github.com/sindresorhus/caprine/blob/master/media/Icon.png