node.js - 如何将远程 webp 图像转换为 png 图像以将其加载到节点画布中
问题描述
通常我通过使用将 png 图像导入 Canvas
const image = Canvas.LoadImage('url.png')
const canvas = Canvas.createCanvas(256,256)
const ctx = canvas.getContext('2d')
ctx.drawImage(image,256,256)
但是当我尝试导入 webp 图像时,我收到一条错误消息,指出不支持 webp。在对节点画布问题的研究中,我发现了这个问题,导入问题似乎已解决,但我现在不明白如何导入 webp 图像。
我尝试使用问题修复中的 Image, ImageFromBuffer(await fetch(url).buffer()) ,但都给出错误。
解决方案
我通过使用库Sharp解决了它。
首先获取文件作为缓冲区
// axios for remote images- maybe fs for local images?
const imageResponse = await axios.get(url, {
responseType: 'arraybuffer',
});
使用Sharp将文件转换为png:
const img = await sharp(imageResponse.data).toFormat('png').toBuffer();
然后你可以使用 loadImage
const file = await loadImage(img).then((image) => {
ctx.drawImage(
image,
256,
256
);
return { buffer: canvas.toBuffer(), mimetype: `image/png` };
});
推荐阅读
- python - 写入文件时如何摆脱\n?
- javascript - Javascript 相当于 LEFT OUTER JOIN 在 WHERE 子句中带有 NULL
- docker - Dockerfile: $HOME 已设置,但在使用它定义其他环境变量时变为空白
- python - Selenium 不在网页上执行 javascript
- intellij-idea - MissingMethodException:没有方法签名:org.spockframework.mock.runtime.InteractionBuilder.setArgListKind()
- python-3.x - 如何让我的打印功能“记住”我之前的声明
- ruby - 您如何从任何给定数组的当前索引中获取前 2 个和后 2 个元素?
- laravel - Laravel:从 Blade 文件中的 javascript 重定向而不使用路由名称
- jekyll - Codekit 和 Jekyll 问题
- neo4j - 我可以查看新关系而不在 neo4j 中实际创建关系吗?