| 68 | // [START functions_imagemagick_blur] |
| 69 | // Blurs the given file using sharp, and uploads it to another bucket. |
| 70 | const blurImage = async (file, blurredBucketName) => { |
| 71 | const tempLocalPath = `/tmp/${path.parse(file.name).base}`; |
| 72 | const tempLocalBlurredPath = `/tmp/blurred-${path.parse(file.name).base}`; |
| 73 | |
| 74 | // Download file from bucket. |
| 75 | try { |
| 76 | await file.download({destination: tempLocalPath}); |
| 77 | |
| 78 | console.log(`Downloaded ${file.name} to ${tempLocalPath}.`); |
| 79 | } catch (err) { |
| 80 | throw new Error(`File download failed: ${err}`); |
| 81 | } |
| 82 | try { |
| 83 | await sharp(tempLocalPath).blur(16).toFile(tempLocalBlurredPath); |
| 84 | |
| 85 | console.log(`Blurred image: ${file.name}`); |
| 86 | } catch (err) { |
| 87 | console.error('Failed to blur image.', err); |
| 88 | throw err; |
| 89 | } |
| 90 | |
| 91 | // Upload result to a different bucket, to avoid re-triggering this function. |
| 92 | const blurredBucket = storage.bucket(blurredBucketName); |
| 93 | |
| 94 | // Upload the Blurred image back into the bucket. |
| 95 | const gcsPath = `gs://${blurredBucketName}/${file.name}`; |
| 96 | try { |
| 97 | await blurredBucket.upload(tempLocalBlurredPath, {destination: file.name}); |
| 98 | console.log(`Uploaded blurred image to: ${gcsPath}`); |
| 99 | } catch (err) { |
| 100 | throw new Error(`Unable to upload blurred image to ${gcsPath}: ${err}`); |
| 101 | } finally { |
| 102 | // Delete the temporary file. |
| 103 | await Promise.allSettled([ |
| 104 | fs.unlink(tempLocalPath), |
| 105 | fs.unlink(tempLocalBlurredPath), |
| 106 | ]); |
| 107 | } |
| 108 | }; |
| 109 | // [END functions_imagemagick_blur] |