How to process images from Google Drive

A common use case for the Photoroom API is to process a large amount of images, which are stored inside a Google Drive folder.

In this tutorial, we'll see how it's possible to process these images by integrating either the Image Editing API or the Remove Background API with a Google Apps Script.

Step 1: Creating a Google Apps Script

If you've never used Google Apps Script before, it's a convenient way to run code that can easily interact with Google services, including Google Drive.

To create an Apps Script, go to your Google Drive, and click on New > More > Google Apps Script:

This will open a new tab that contains a development environment:

The first thing we'll do is to allow the script to interact with Google Drive.

To do that, click on the “+” button next to Services:

Then proceed to add both the Drive API:

You should now see the Drive services available in your development environment:

Now that our environment is set up, it's time to write some code!

You can remove the sample code function myFunction() and replace it with this code:

// Customizable variables
const INPUT_FOLDER_ID = "YOUR_INPUT_FOLDER_ID";
const OUTPUT_FOLDER_ID = "YOUR_INPUT_FOLDER_ID";
const API_KEY = "YOUR_API_KEY";
const SANDBOX_MODE = false;
// Params can be expressed as GET params shape
const EDIT_PARAMS = "background.color=transparent&background.scaling=fill&outputSize=1000x1000&padding=0.1";
// Or as direct payload
// const EDIT_PARAMS = {
//   "background.color": "transparent",
//   "background.scaling": "fill",
//   outputSize: "1000x1000",
//   padding: 0.1
// }

const inputFolder = DriveApp.getFolderById(INPUT_FOLDER_ID);
const outputFolder = DriveApp.getFolderById(OUTPUT_FOLDER_ID);
const formDataPayload = generatePayloadFromParams(EDIT_PARAMS);

// The main function to execute the script
function imageEditingAPIMain() {

  const imagesToProcess = [];
  const files = inputFolder.getFiles();

  while (files.hasNext()) {
    const file = files.next();
    if (isImageFile(file) && !isFileProcessed(file.getName())) {
      imagesToProcess.push(file);
    }
  }

  console.log(`Found ${imagesToProcess.length} images to process`);

  const batchSize = 8; // Adjust this based on your API's rate limits

  // Process images and send them to the OUTPUT_FOLDER
  for (let i = 0; i < imagesToProcess.length; i += batchSize) {
    const batch = imagesToProcess.slice(i, i + batchSize);

    const requests = batch.map((imageToProcess) => {
      const originUrl = "https://image-api.photoroom.com";

      return {
        url: `${originUrl}/v2/edit`,
        method: "post",
        headers: {
          "x-api-key": `${SANDBOX_MODE ? "sandbox_" : ""}${API_KEY}`,
        },
        payload: {
          ...formDataPayload,
          imageFile: imageToProcess.getBlob(),
        },
        muteHttpExceptions: true,
      };
    });

    const responses = UrlFetchApp.fetchAll(requests);

    for (let j = 0; j < responses.length; j++) {
      const response = responses[j];
      const imageToProcess = batch[j];

      if (response.getResponseCode() === 200) {
        try {
          const processedImageBlob = response.getBlob();
          outputFolder.createFile(processedImageBlob.setName(imageToProcess.getName()));

          console.log(`Processed '${imageToProcess.getName()}'`);
        } catch (e) {
          console.error(`Failed to process ${imageToProcess.getName()}: ${e.message}`);
        }
      } else {
        console.error(`Failed to process ${imageToProcess.getName()}: ${response.getContentText()}`);
      }
    }
  }
}

function isFileProcessed(fileName) {
  const files = outputFolder.getFilesByName(fileName);
  return files.hasNext();
}

function isImageFile(file) {
  const mimeType = file.getMimeType();
  return mimeType.indexOf("image/") === 0;
}

function generatePayloadFromParams(editParams) {
  if (typeof editParams === "object") {
    return editParams;
  }

  return editParams
    .split("&")
    .map((param) => param.split("="))
    .reduce((acc, [key, value]) => {
      acc[key] = decodeURIComponent(value);
      return acc;
    }, {});
}

There's quite a bit of code. Fortunately, you will only need to configure a few parts:

  1. update const API_KEY with your Photoroom API key

If you don't have an API key, here are the steps to create yours.

  1. update const INPUT_FOLDER_ID and const OUTPUT_FOLDER_ID with respectively the id of the Google Drive folder where you want to read the input images and save the result images

To get the id of a Google Drive folder, you just need to look at the folder's URL:

https://drive.google.com/drive/u/0/folders/THIS_IS_THE_FOLDER_ID

  1. set the value of const SANDBOX_MODE depending on whether or not you want to use Sandbox mode

  2. set the value of const EDIT_PARAMS with the edits that you want to apply to your images

To define which edits you want to apply, we recommend that you use our Interactive API Playground.

That's all the changes you need to make, the rest of the code can be used as-is.

Step 2: Running the Google Apps Script

Then, the next step is to run the script!

To execute the script, you just need to click on the button Run:

The first time you run the script, you'll be prompted to give it permission to access your Google Sheets and Google Drive.

While the script is running, you'll see appear the execution log which lets you monitor its progress and will provide useful debug information should an error occur.

The Google Drive folder whose id you used should also contain the result images:

Step 3: Scheduling Execution of the Google Apps Script

In addition to manually executing the Google Apps Script from the development environment, it's also possible to schedule its execution at predefined times.

To schedule the execution of the script, click on Trigger in the left menu, then on Add Trigger:

Then make sure that the function to be executed is indeed the correct one, then select the periodicity at which you want your script to be executed, and finally save the trigger:

Conclusion

In this tutorial, we saw how to use a Google Apps Script to easily process images stored inside Google Drive through the Photoroom API.

It's worth noting that a very similar approach can also be used in the situation where you want to process images stored in another service, using a combination of a Google Apps Script and a Google Sheet.

Last updated