Firebase 函数 - 使用 ImageMagick 模糊图像失败,错误代码为 4

Firebase Functions - Blurring image with ImageMagick fails with error code 4

我正在尝试编写一个模糊图像的基本 firebase 函数。代码主要基于firebase函数示例:

async function blurImage(filePath, bucketName, metadata) {
  const tempLocalFile = path.join(os.tmpdir(), filePath);
  const tempLocalDir = path.dirname(tempLocalFile);
  const bucket = admin.storage().bucket(bucketName);

  // Create the temp directory where the storage file will be downloaded.
  await mkdirp(tempLocalDir);

  // Download file from bucket.
  await bucket.file(filePath).download({destination: tempLocalFile});

  // Blur the image using ImageMagick.
  await spawn('convert', [tempLocalFile, '-channel', 'RGBA', '-blur', '0x8', tempLocalFile]);

  // Uploading the Blurred image.
  await bucket.upload(tempLocalFile, {
    destination: `${BLURRED_FOLDER}/${filePath}`,
    metadata: {metadata: metadata}, // Keeping custom metadata.
  });

  // Clean up the local file
  fs.unlinkSync(tempLocalFile);
}

我正在尝试使用 firebase functions:shelltestData.json 文件在本地进行测试,但是不断收到错误消息:

ChildProcessError: "convert C:\filePath -channel RGBA -blur 0x8 C:\filePath" failed with code 4

谁能告诉我如何解决这个问题?

如果您使用此代码而不是 spawn 来模糊图像,您将看到更详细的错误版本:

const gm = require('gm').subClass({imageMagick: true});

...

await new Promise((resolve, reject) => {
    gm(tempLocalFile)
      .blur(0, 16)
      .write(tempLocalFile, (err, stdout) => {
        if (err) {
          console.error('Failed to blur image.', err);
          reject(err);
        } else {
          console.log(`Blurred image: ${filePath}`);
          resolve(stdout);
        }
    });
  });

该错误将告诉您无法找到 gm/convert 二进制文件。由于您使用的是 Windows,请安装 binaries and follow the instructions from this answer。我会在这里注明:

If you use gm on windows you should download windows binaries here and add gm.exe to your windows environment PATH variable. After that you have to restart your PC. Then install corresponding node package with npm install gm and it will work.

其他参考资料:

Another code example to blur images