Search code examples
firebasegoogle-cloud-functionsimagemagick-convert

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


I'm trying to write a basic firebase function which blurs images. The code is based mainly on the firebase function samples:

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);
}

I am trying to test this locally using firebase functions:shell and a testData.json file, however keep getting the error:

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

Can someone please tell me how to fix this?


Solution

  • If you use this code to blur the image instead of spawn, you'll see a more detailed version of the error:

    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);
            }
        });
      });
    

    The error will tell you that gm/convert binaries can't be found. Since you're using Windows, install the binaries and follow the instructions from this answer. I will note it here:

    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.

    Additional References:

    Another code example to blur images