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 all the sample code function myFunction() { } and replace it with this code:
// Customizable variablesconstINPUT_FOLDER_ID="REPLACE_WITH_YOUR_INPUT_FOLDER_ID";constOUTPUT_FOLDER_ID="REPLACE_WITH_YOUR_OUTPUT_FOLDER_ID";constAPI_KEY="REPLACE_WITH_YOUR_API_KEY";constSANDBOX_MODE=false;// Params can be expressed as GET params shapeconstEDIT_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// }constinputFolder=DriveApp.getFolderById(INPUT_FOLDER_ID);constoutputFolder=DriveApp.getFolderById(OUTPUT_FOLDER_ID);constformDataPayload=generatePayloadFromParams(EDIT_PARAMS);// The main function to execute the scriptfunctionimageEditingAPIMain() {constimagesToProcess= [];constfiles=inputFolder.getFiles();while (files.hasNext()) {constfile=files.next();if (isImageFile(file) &&!isFileProcessed(file.getName())) {imagesToProcess.push(file); } }console.log(`Found ${imagesToProcess.length} images to process`);constbatchSize=8; // Adjust this based on your API's rate limits// Process images and send them to the OUTPUT_FOLDERfor (let i =0; i <imagesToProcess.length; i += batchSize) {constbatch=imagesToProcess.slice(i, i + batchSize);constrequests=batch.map((imageToProcess) => {constoriginUrl="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, }; });constresponses=UrlFetchApp.fetchAll(requests);for (let j =0; j <responses.length; j++) {constresponse= responses[j];constimageToProcess= batch[j];if (response.getResponseCode() ===200) {try {constprocessedImageBlob=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()}`); } } }}functionisFileProcessed(fileName) {constfiles=outputFolder.getFilesByName(fileName);returnfiles.hasNext();}functionisImageFile(file) {constmimeType=file.getMimeType();returnmimeType.indexOf("image/") ===0;}functiongeneratePayloadFromParams(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:
⚠️ Make sure not to includesandbox_ when copy/pasting your API key ⚠️
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:
⚠️ Make sure not to includesandbox_ when copy/pasting your API key ⚠️
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:
set the value of const BACKGROUND_REMOVAL_PARAMS to configure the parameters of the API call
The documentation of each of these parameters is available here.
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.