【问题标题】:Convert image format on Cloud Storage with Cloud Functions and Sharp does not work使用 Cloud Functions 和 Sharp 在 Cloud Storage 上转换图像格式不起作用
【发布时间】:2021-01-27 15:47:53
【问题描述】:

将图片上传到 Firebase Cloud Storage 时,我想调整图片大小并将图片格式转换为 webp。所以我用 Cloud Function 创建了一个触发器。为此,我使用了 Node.js Sharp 库。

Cloud Function 可以正确调整图像大小,但它始终让我保持原始格式。

这是转换和调整大小的代码:

function resize(originalFile, resizedFile, size) {
  let height, width;
  if (size.indexOf(",") !== -1) {
    [width, height] = size.split(",");
  } else if (size.indexOf("x") !== -1) {
    [width, height] = size.split("x");
  } else {
    throw new Error("height and width are not delimited by a ',' or a 'x'");
  }
  return sharp(originalFile)
    .rotate()
    .toFormat("webp", {
      quality: 80,
      force: true
    })
    .resize(parseInt(width, 10), parseInt(height, 10), {
      fit: "inside",
      withoutEnlargement: true,
    }).toFile(resizedFile);
}

在本地的node.js项目上运行,效果很好。

更新

我使用的是 Sharp 0.26.1,我也按照建议尝试了以前的版本,但没有任何改变。

我也试过了,用fs-extra库写文件,结果还是一样:resize和compression正常,而格式转换不行。

async function resize(originalFile, resizedFile, size) {
  let height, width;
  if (size.indexOf(",") !== -1) {
    [width, height] = size.split(",");
  }
  else if (size.indexOf("x") !== -1) {
    [width, height] = size.split("x");
  }
  else {
    throw new Error("height and width are not delimited by a ',' or a 'x'");
  }


  const data = await sharp(originalFile)
    .rotate()
    .toFormat("webp")
    .resize(parseInt(width, 10), parseInt(height, 10), {
      fit: "inside",
      withoutEnlargement: true,
    })
    .webp({
      quality: 80,
      force: true
    })
    //.toFile(resizedFile);
    .toBuffer();
    fs.writeFileSync(resizedFile, data);

}

再次,在本地启动代码,它工作正常。 (当我说“本地”时,我的意思是在 node.js 项目上。无法在本地测试此 Cloud Function,因为没有官方的 Cloud Storage 本地模拟器)

【问题讨论】:

    标签: javascript node.js firebase google-cloud-functions sharp


    【解决方案1】:

    我已经为此奋斗了好几个小时,这最终对我有用。确保您使用用于上传到 AWS/Azure/Digital Ocean 的上传标头设置的 mimetype 是“image/webp”

    【讨论】:

    • 这看起来更像是评论而不是答案。
    【解决方案2】:

    不要只使用toFormat(),而是尝试使用它,然后调用webp(),如下所示:

    return sharp(originalFile)
        .rotate()
        .resize(parseInt(width, 10), parseInt(height, 10), {
            fit: "inside",
            withoutEnlargement: true,
        })
        .toFormat("webp")
        .webp({
            quality: 80,
            force: true
        });
        .toFile(resizedFile);
    

    这应该可以正常工作。

    【讨论】:

    • 我已经试过了,我又试了一次,还是不行。我认为问题可能是“webp”,但对于其他格式它也不起作用。
    • 你是如何调用函数的? .toFile(resizedFile) 返回一个承诺,所以它可能是一个同步问题。
    • 函数被同步调用(使用表达式“await”)。事实上,调整大小可以正常工作。会不会是导入sharp库的问题?还是操作系统问题?
    • 我会说你在代码中所做的一切都是正确的,问题很可能出在Sharp库本身,尝试使用它的不同版本作为测试。
    • 新旧版本都试过了,可惜都不管用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 2019-09-27
    • 2021-07-30
    • 2019-06-01
    • 2019-09-21
    • 2017-09-30
    相关资源
    最近更新 更多