如何在 Node.js 中将 JPG 图像转换为 WEBP 格式?

2024-02-21

我正在尝试使用react.Js上传图像并使用multer中间件将该图像保存在node.Js中。这是完美的,但现在我想使用 webp-converter 将该图像转换为 WEBP 格式,反之亦然。

但我收到此错误:

 Error: Command failed: E:\Zegal\node_modules\webp-converte
 ib/libwebp_win64/bin/cwebp.exe -q 80 2a3279b820cc23939eea0295228423ee-- 
 inspironal-quote-about-life-inspiring-words.jpg -o output.webp
 SHCreateStreamOnFileA(filename, STGM_READ, stream) failed 80070002
 Error opening input file 2a3279b820cc23939eea0295228423ee--inspirational-quo
 about-life-inspiring-words.jpg (80070002)
 OpenInputStream(filename, &stream) failed 80070002
 cannot open input file '2a3279b820cc23939eea0295228423ee--inspirational-quot
 bout-life-inspiring-words.jpg'
 Error! Could not process file 2a3279b820cc23939eea0295228423ee--inspirationa
 uote-about-life-inspiring-words.jpg
 Error! Cannot read input picture file '2a3279b820cc23939eea0295228423ee--ins
 ational-quote-about-life-inspiring-words.jpg'

如何使用 multer 和 WEBP 在节点中解决这个问题?有没有 其他转换解决方案?

const multer = require('multer');
const webp = require('webp-converter');
const path = require('path');
const storage = multer.diskStorage({
    destination: './public/images',
    filename(req, file, cb) {
        cb(null, `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`)
    }
});

const upload = multer({
    storage,
    fileFilter: function (req, file, cb) {
        checkFileType(file, cb)
    }
}).single("image");

checkFileType = (file, cb) => {
    console.log("check file", file);
    const requireMimetype = "image/jpeg";
    const checkMimeType = file.mimetype == requireMimetype ? true : false;
    console.log("checkMimeType", checkMimeType);
    if (checkMimeType) {
        webp.cwebp(file.originalname, "output.webp", "-q 80", function (status) {
            console.log(status);
        });
        return cb(null, true)
    } else {
        cb("Error:Only jpg images are allowed.")
    }
}

module.exports = upload;

我找到了一个简单的方法来做到这一点。

const sharp = require('sharp');


console.log(req.files.image, "form image is here"); 
console.log(req.files.image.data, "form image buffer data is here");

sharp(req.files.image.data)            
.rotate()            
.resize(200)            
.toBuffer()            
.then( newBuffer => { 

//changing the old jpg image buffer to new webp buffer
 req.files.image.data = newBuffer;

//moving the new webq image to server public folders
 req.files.image.mv(appRoot+'/uploads/images/'+ Date.now() + '.webp', function(err) {                
  if (err) {                    
     return res.status(500).send(err);                
  }
   res.status(200).json({
      message : "image uploaded successfully" 
  })
 })            
})            
.catch( err => { console.log(err) });

希望能帮助到你。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Node.js 中将 JPG 图像转换为 WEBP 格式? 的相关文章

随机推荐

  • Windows Mobile 应用程序 - 通过 MMS 协议播放流?

    NOTE 这个问题被重新提出是因为我在上一个问题中不小心点击了社区维基 显然这并没有以声誉的形式提供足够的激励来让人们回答这个问题 这是旧问题的链接 请不要重复这些答案 无论如何它们并不完全有帮助 链接到原始问题 https stackov
  • 将分支合并到目录 GIT

    我有一个名为Project 然后我有一个名为payment其中包含应用程序的所有项目文件 我想合并分支payment进入我的主分支 但在文件夹 目录内 换句话说 项目分支 gt 支付申请 文件夹 gt 支付分支文件 第一次 git chec
  • C++ 中嵌套类型/类的前向声明

    我最近陷入了这样的情况 class A public typedef struct class B C D someField class C public typedef struct class D A B someField 通常你可
  • 使用 anaconda python3 安装 opencv 3.1?

    如何使用 anaconda python3 安装 opencv opencv 获取了我的 python3 可执行文件 Python 2 Interpreter usr bin python2 7 ver 2 7 12 Libraries u
  • Vue Router 推送错误:避免了到当前位置的冗余导航

    有没有办法避免错误 避免冗余导航到当前位置 我需要进行分页 方法如下 handlePageChange page number void const query this route query page page toString thi
  • ActiveJob GlobalID 和内存中 ActiveRecord 对象

    我正在使用排队系统 Sidekiq 并且希望迁移到 ActiveJob 以获得性能优势 因为不必每次将 ActiveRecord 对象传递给工作人员时都查询数据库 我想询问并确认 因为我不是 100 确定 但我的理解是 当 ActiveJo
  • 使用依赖属性和样式触发器时,“...不是 DependencyProperty”

    在我的用户控件中 public ODIF DeviceChannel Channel get return ODIF DeviceChannel GetValue ChannelDP set SetValue ChannelDP value
  • TableDnD onDrop 事件未触发

    我确信这是非常简单的事情 通常都是如此 sort table tableDnD onDragClass dnd drag onDragStart function table row console log start drag onDro
  • 如何从标准输入中读取一行,并将其余行传递给子进程?

    If you readline from sys stdin 将其余部分传递给子进程似乎不起作用 import subprocess import sys header sys stdin buffer readline print hea
  • 如何在servlet中获取客户端的远程地址?

    有什么办法可以获取到服务器的客户端的原始IP地址吗 我可以用request getRemoteAddr 但我似乎总是获得代理或网络服务器的IP 我想知道客户端用于连接到我的 IP 地址 无论如何 我能得到它吗 尝试这个 public sta
  • Visual Studio 2012 是否利用所有可用的 CPU 内核?

    我计划在 Visual Studio 2012 和 Windows 7 64 位下构建一台新的非常快的开发计算机 我正在购买所有快速组件 例如 SSD 和 16G RAM 我想知道是否视觉工作室2012旨在利用所有可用的 CPU 内核 我正
  • 每次出现错误时使用 prometheus 创建警报

    我是普罗米修斯和警报系统的新手 我开发了一个微服务并添加了指标代码 以便在出现错误时获取增量总数 现在我正在尝试创建一个警报 以便每当错误增加时 它应该标记出来并发送邮件 但我无法针对这种情况形成正确的查询 我使用了诸如 error tot
  • CoreMotion 陀螺仪苹果手表

    我正在尝试访问苹果手表的陀螺仪 据我所知 它可以在 watchos 3 中使用 不幸的是我无法让它工作 它不断返回 陀螺仪不可用 因此 MotionManager isGyroAvailable 始终为 false 这是我的代码 任何帮助
  • Kotlin 本地函数必须在使用前声明

    在这个简单的代码示例中 fun testLocalFunctions aLocalFun compiler error unresolved reference at aLocalFun fun aLocalFun aLocalFun no
  • 如何保持领域数据与输入的顺序相同

    我有一个应用程序 需要将数据按照输入的顺序保存 数据被输入到 List 属性中 一切都很顺利 直到我必须删除一个项目 当删除发生时 列表中的最后一项将取代被删除的一项 UITableView 显示正确的项目数 但与领域列表不同步 一个例子是
  • R中的顺序混淆矩阵

    我根据 3 个类别的观察结果及其预测创建了一个混淆矩阵 classes c Underweight Normal Overweight 当我计算混淆矩阵时 它会按字母顺序组织表中的类 这是我的代码 Confusion matrix Obse
  • 为什么此解释中没有使用密钥?

    我期望这个查询使用密钥 mysql gt DESCRIBE TABLE Foo Field Type Null Key Default Extra id bigint 20 NO PRI NULL auto increment name v
  • 如何正确编写 Swift UI Toggle 的 UI 测试

    有谁知道如何正确编写 Toggle 的 UI 测试 即使在一个全新的项目中 整个 UI 中只有一个切换而没有其他内容 我仍然会收到此类错误 Failed to get matching snapshot Multiple matching
  • OpenCV detectorMultiScale() 参数的推荐值

    推荐的参数是什么CascadeClassifier detectMultiScale http docs opencv org modules objdetect doc cascade classification html cascad
  • 如何在 Node.js 中将 JPG 图像转换为 WEBP 格式?

    我正在尝试使用react Js上传图像并使用multer中间件将该图像保存在node Js中 这是完美的 但现在我想使用 webp converter 将该图像转换为 WEBP 格式 反之亦然 但我收到此错误 Error Command f