Recently I am using JS to do fun things and need to process pictures. There are many tutorials on the Internet with various methods, and some methods may not necessarily work. This article will share with you a method verified by the author to use NodeJS to process images.
npm i gm
gm is a Node library that provides some JS APIs so that developers can process images. But it relies on GraphicsMagick, or ImageMagick underneath. In fact, gm is the command line for calling those two tools.
In other words, in addition to installing gm, we also need to install either GraphicsMagick or ImageMagick.
ImageMagickThe author is on MacOS and directly chose to install ImageMagick.
According to the official website command, only 1 line of code is needed (provided you have installed brew on your Mac):
brew install imagemagick --with-webp
Let me introduce the parameter --with-webp
. You can delete it, but if you want to process images in webp format, you must add it.
It is more convenient to use brew. You don’t have to worry about environment variables.
GraphicsMagick
Of course, if you don’t use ImageMagick, you can use GraphicsMagick:
brew install graphicsmagick
At first I chose to install ImageMagick, and when I wrote this, I always got an error:
const gm = require('gm'); gm('Picture file path').crop(width, height, 0, 0).resize(width2, height2).quality(quality).write('Output file path', function (err) { if (err) { return console.log(err); } else { console.log('success'); } });
If you want to use ImageMagick, the above way of writing is actually wrong. You should write it like this, clearly specifying that I want to use the ImageMagick
tool:
const g = require('gm'); const gm = g.subClass({imageMagick: true}); gm('Picture file path').crop(width, height, 0, 0).resize(width2, height2).quality(quality).write('Output file path', function (err) { if (err) { return console.log(err); } else { console.log('success'); } });
Record the commonly used functions of gm for your reference:
Note: gm can be called in a chain, and it is very fun to write. It reads the image file from gm(filename), processes it layer by layer, and finally writes it to the file.write(filename, callback).
Zoom picture
.resize(width, height)
Crop picture
.crop(width, height, x, y)
Rotate picture
.rotate(color, deg)
color is the background color (if the deg rotation angle is not a multiple of 90, the background color comes in handy, just use the format '#ededed')