I was using gm
for resizing images. Now I learn about webp
to speed up my site. So I want to convert images into webp
using same library. But the following does not work.
How can I convert images into webp
by gm
?
function resize(last) {
self.resize(width, height)
.quality(80)
.strip()
.gravity('Center')
.toBuffer(imageType, function(err, buffer) {
if (err) last(err);
else last(null, buffer);
});
},
EDIT
gm('thumb_3.JPG')
.toBuffer('webp', (err, buffer) => {
fs.writeFile('buffer.webp', buffer, console.log)
})
I use this code also
All you have to do is call:
.toBuffer('webp', (err, buffer) => { /* ... */ })
Or using streams
.stream('webp');
But for it to work, you have to install imagick explicitly with webp
brew install imagemagick --with-webp
Otherwise install graphicsmagick
that supports webp
directly.
Depending on your OS:
Ubuntu/Debian
sudo apt-get install graphicsmagick
Mac OS
brew install graphicsmagick
For windows or other OS, check:
Working example:
const fs = require('fs');
const gm = require('gm');
gm('/tmp/img.jpg')
.stream('webp')
.pipe(fs.createWriteStream('/tmp/img.webp'));
gm('/tmp/img.jpg')
.toBuffer('webp', (err, buffer) => {
fs.writeFile('/tmp/img-buffer.webp', buffer, console.log)
})