ImageMagick Tutorial

This tutorial demonstrates using Cloud Functions, the Google Cloud Vision API, and ImageMagick to detect and blur offensive images that get uploaded to a Cloud Storage bucket.

Objectives

  • Deploy a storage-triggered Background Cloud Function.
  • Use the Cloud Vision API to detect violent or adult content.
  • Use ImageMagick to blur offensive images.
  • Test the function by uploading an image of a flesh-eating zombie.

Costs

This tutorial uses billable components of Cloud Platform, including:

  • Google Cloud Functions
  • Google Cloud Storage
  • Google Cloud Vision API

Use the Pricing Calculator to generate a cost estimate based on your projected usage.

New Cloud Platform users might be eligible for a free trial.

Before you begin

  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. Select or create a GCP project.

    Go to the Manage resources page

  3. Make sure that billing is enabled for your project.

    Learn how to enable billing

  4. Enable the Cloud Functions, Cloud Storage, and Cloud Vision APIs.

    Enable the APIs

  5. Install and initialize the Cloud SDK.
  6. Update and install gcloud components:

    Node.js 6

    gcloud components update
  7. Prepare your development environment.

Visualizing the flow of data

The flow of data in the ImageMagick tutorial application involves several steps:

  1. An image is uploaded to a Cloud Storage bucket.
  2. The Cloud Function analyzes the image using the Cloud Vision API.
  3. If violent or adult content is detected, the Cloud Function uses ImageMagick to blur the image.
  4. The blurred image is uploaded over the original image in the Cloud Storage bucket.

Preparing the application

  1. Create a Cloud Storage bucket for uploading images, where YOUR_IMAGE_BUCKET_NAME is a globally unique bucket name:

    gsutil mb gs://YOUR_IMAGE_BUCKET_NAME
    

  2. Clone the sample app repository to your local machine:

    Node.js 6

    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

    Alternatively, you can download the sample as a zip file and extract it.

  3. Change to the directory that contains the Cloud Functions sample code:

    Node.js 6

    cd nodejs-docs-samples/functions/imagemagick/

Understanding the code

Importing dependencies

The application must import several dependencies in order to interact with Google Cloud Platform services, ImageMagick, and the file system:

Node.js 6

const exec = require('child_process').exec;
const fs = require('fs');
const path = require('path');
const storage = require('@google-cloud/storage')();
const vision = require('@google-cloud/vision').v1p1beta1;

const client = new vision.ImageAnnotatorClient();

Analyzing images

The following function is invoked when an image is uploaded to the Cloud Storage bucket you created for storing images. The function uses the Cloud Vision API to detect violent or adult content in uploaded images.

Node.js 6

// Blurs uploaded images that are flagged as Adult or Violence.
exports.blurOffensiveImages = (event) => {
  const object = event.data;

  // Exit if this is a deletion or a deploy event.
  if (object.resourceState === 'not_exists') {
    console.log('This is a deletion event.');
    return;
  } else if (!object.name) {
    console.log('This is a deploy event.');
    return;
  }

  const file = storage.bucket(object.bucket).file(object.name);
  const filePath = `gs://${object.bucket}/${object.name}`;

  console.log(`Analyzing ${file.name}.`);

  return client.safeSearchDetection(filePath)
    .catch((err) => {
      console.error(`Failed to analyze ${file.name}.`, err);
      return Promise.reject(err);
    })
    .then(([result]) => {
      const detections = result.safeSearchAnnotation;

      if (detections.adult === 'VERY_LIKELY' ||
          detections.violence === 'VERY_LIKELY') {
        console.log(`The image ${file.name} has been detected as inappropriate.`);
        return blurImage(file);
      } else {
        console.log(`The image ${file.name} has been detected as OK.`);
      }
    });
};

Blurring images

The following function is called when violent or adult content is detected in an uploaded image. The function downloads the offensive image, uses ImageMagick to blur the image, and then uploads the blurred image over the original image.

Node.js 6

// Blurs the given file using ImageMagick.
function blurImage (file) {
  const tempLocalFilename = `/tmp/${path.parse(file.name).base}`;

  // Download file from bucket.
  return file.download({ destination: tempLocalFilename })
    .catch((err) => {
      console.error('Failed to download file.', err);
      return Promise.reject(err);
    })
    .then(() => {
      console.log(`Image ${file.name} has been downloaded to ${tempLocalFilename}.`);

      // Blur the image using ImageMagick.
      return new Promise((resolve, reject) => {
        exec(`convert ${tempLocalFilename} -channel RGBA -blur 0x24 ${tempLocalFilename}`, { stdio: 'ignore' }, (err, stdout) => {
          if (err) {
            console.error('Failed to blur image.', err);
            reject(err);
          } else {
            resolve(stdout);
          }
        });
      });
    })
    .then(() => {
      console.log(`Image ${file.name} has been blurred.`);

      // Upload the Blurred image back into the bucket.
      return file.bucket.upload(tempLocalFilename, { destination: file.name })
        .catch((err) => {
          console.error('Failed to upload blurred image.', err);
          return Promise.reject(err);
        });
    })
    .then(() => {
      console.log(`Blurred image has been uploaded to ${file.name}.`);

      // Delete the temporary file.
      return new Promise((resolve, reject) => {
        fs.unlink(tempLocalFilename, (err) => {
          if (err) {
            reject(err);
          } else {
            resolve();
          }
        });
      });
    });
}

Deploying the function

  1. To deploy your Cloud Function with a storage trigger, run the following command in the imagemagick directory:

    Node.js 6

    gcloud functions deploy blurOffensiveImages --trigger-bucket YOUR_IMAGE_BUCKET_NAME

    where YOUR_IMAGE_BUCKET_NAME is the name of the Cloud Storage bucket for uploading images.

Uploading an image

  1. Upload an offensive image, such as this image of a flesh-eating zombie:

    gsutil cp zombie.jpg gs://YOUR_IMAGE_BUCKET_NAME
    

    where YOUR_IMAGE_BUCKET_NAME is the Cloud Storage bucket you created earlier for uploading images.

  2. Watch the logs to be sure the executions have completed:

    gcloud functions logs read --limit 100
    

  3. You can view the blurred images in the Cloud Storage bucket you created earlier for uploading images.

Cleaning up

To avoid incurring charges to your Google Cloud Platform account for the resources used in this tutorial:

Deleting the project

The easiest way to eliminate billing is to delete the project you created for the tutorial.

To delete the project:

  1. In the GCP Console, go to the Projects page.

    Go to the Projects page

  2. In the project list, select the project you want to delete and click Delete project. After selecting the checkbox next to the project name, click
      Delete project
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

Deleting the Cloud Function

Deleting Cloud Functions does not remove any resources stored in Cloud Storage.

To delete the Cloud Function you deployed in this tutorial, run the following command:

Node.js 6

gcloud functions delete blurOffensiveImages 

You can also delete Cloud Functions from the Google Cloud Platform Console.

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Functions Documentation