简体   繁体   English

如何在node.js中使用gm将图像转换为webp

[英]How to convert image into webp using gm in node.js

I was using gm for resizing images. 我正在使用gm调整图像大小。 Now I learn about webp to speed up my site. 现在,我了解了webp来加速我的网站。 So I want to convert images into webp using same library. 所以我想使用相同的库将图像转换为webp But the following does not work. 但是以下方法不起作用。

How can I convert images into webp by gm ? 如何通过gm将图像转换为webp

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 或使用streams

.stream('webp');

But for it to work, you have to install imagick explicitly with webp 但要使其正常工作,您必须使用webp显式安装imagick

brew install imagemagick --with-webp

Otherwise install graphicsmagick that supports webp directly. 否则,请直接安装支持webp graphicsmagick

Depending on your OS: 取决于您的操作系统:

Ubuntu/Debian Ubuntu的/ Debian的

sudo apt-get install graphicsmagick

Mac OS 苹果系统

brew install graphicsmagick

For windows or other OS, check: 对于Windows或其他操作系统,请检查:


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)
  })

For me, I am using gm version 1.3.30 and it does not include webp automatically. 对我来说,我正在使用gm版本1.3.30 ,它不自动包含webp instead, you need to install it manually 相反,您需要手动安装

To check, gm -version 要检查, 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一起安装

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. 包括webp将解决Stream yields empty buffer也会Stream yields empty buffer的问题。

good luck ! 祝好运 !

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM