3

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

Haseeb Ahmad
  • 7,914
  • 12
  • 55
  • 133

2 Answers2

2

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)
  })
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98
2

For me, I am using gm version 1.3.30 and it does not include webp automatically. instead, you need to install it manually

To check, gm -version

Feature Support:
  Native Thread Safe       yes
  Large Files (> 32 bit)   yes
  Large Memory (> 32 bit)  yes
  BZIP                     yes
  ...
  WebP                     no
  WMF                      no
  X11                      no
  XML                      yes
  ZLIB                     yes

to install with brew,

brew install graphicsmagick --with-webp

if you already installed it before then

brew reinstall graphicsmagick --with-webp

including webp will solve the issue Stream yields empty buffer as well.

good luck !

Daniel
  • 606
  • 7
  • 23