【问题标题】:Resize image before saving with Node.js在使用 Node.js 保存之前调整图像大小
【发布时间】:2022-02-02 19:20:56
【问题描述】:

我有这样的上传功能:

app.post("/upload", function (req, res) {
  let base64 = req.body.image.replace(/^data:image\/png;base64,/, "");
  binaryData = Buffer.from(base64, "base64").toString("binary");

  fs.writeFile(
    "./pictures/" + Date.now() + ".png",
    binaryData,
    "binary",
    function (err) {
      if (err) {
        console.log(err);
      }
    }
  );

  fs.writeFile(
    "./thumbnails/" + Date.now() + ".png",
    binaryData,
    "binary",
    function (err) {
      if (err) {
        console.log(err);
      }
    }
  );

第一部分将图像保存到“图片”文件夹中。 没问题,这里没什么可做的。

第二部分将相同的图像保存到“缩略图”文件夹中。 我需要做的是在保存之前调整图像大小,只在该文件夹中调整大小的图像。

【问题讨论】:

  • 您可能需要为此包含一些图像处理库

标签: node.js


【解决方案1】:

您可以尝试使用 Sharp 库:https://sharp.pixelplumbing.com/api-resize

app.post("/upload", function (req, res) {
let base64 = req.body.image.replace(/^data:image\/png;base64,/, "");
binaryData = Buffer.from(base64, "base64").toString("binary");

fs.writeFile(
    "./pictures/" + Date.now() + ".png",
    binaryData,
    "binary",
    function (err) {
        if (err) {
            console.log(err);
        }
    }
);

sharp(binaryData)
    .resize({ width: 100 })
    .toBuffer()
    .then(data => {
        // 100 pixels wide, auto-scaled height
        fs.writeFile(
            "./thumbnails/" + Date.now() + ".png",
            data,
            "binary",
            function (err) {
                if (err) {
                    console.log(err);
                }
            }
        )
    })
})

【讨论】:

  • 完美,非常感谢。但是我不能用 npm 安装Sharp。我收到此错误:安装错误:无法验证第一个证书。我尝试执行 npm install sharp --unsafe-perms 但没有任何变化。
猜你喜欢
  • 2012-12-14
  • 2011-09-01
  • 1970-01-01
  • 2020-02-16
  • 1970-01-01
  • 2018-08-28
  • 2013-07-26
  • 2013-05-09
  • 2011-07-31
相关资源
最近更新 更多