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