How to List Images from a Google Drive Folder and Generate Descriptions Using Gemini AI

πŸ“˜ Introduction

Have you ever needed to list image files from a Google Drive folder and generate descriptions for each image automatically? This process can be time-consuming if done manually, but with Google Apps Script and Gemini AI, you can automate the entire workflow.

In this blog post, you’ll learn how to:

  • List all images in a Google Drive folder.
  • Extract image details like file name, URL, and MIME type.
  • Generate AI-powered image descriptions using Gemini AI.
  • Store all image details in a Google Sheet for future reference.

This process is perfect for image cataloging, SEO optimization, and content management.


πŸ“˜ Key Features

  1. List Image Files from a Google Drive Folder
  2. Convert Images to Base64 β€” Send images to Gemini AI.
  3. Generate Descriptions Using Gemini AI β€” Get a detailed description of each image.
  4. Export Image Details to Google Sheets β€” List file name, URL, MIME type, and AI-generated descriptions.

πŸ“˜ Prerequisites

  1. Google Drive Folder β€” Create a folder where your image files are stored.
  2. Google Sheet β€” Create a Google Sheet with a sheet named list.
  3. Gemini AI API Key β€” Get an API key from Google Cloud Console.

πŸ“˜ Full Apps Script

This script automates the entire process of listing images, extracting their details, and creating descriptions.

const IMAGEFOLDER = 'YOUR_FOLDER_ID_HERE'; // Replace with the ID of your image folder
const SHEETID = 'YOUR_SHEET_ID_HERE'; // Replace with the ID of your Google Sheet
const GEMIKEY = 'YOUR_GEMINI_API_KEY_HERE'; // Replace with your Gemini API Key

/**
* List all image files in a folder, get file info, and generate AI descriptions.
*/
function listFilesInFolder() {
const folderId = IMAGEFOLDER;
const folder = DriveApp.getFolderById(folderId);
const files = folder.getFiles();
const sheet = SpreadsheetApp.openById(SHEETID).getSheetByName('list');

// Clear the sheet before adding new data
sheet.clear();
sheet.appendRow(["File Name", "File URL", "MIME Type", "AI Description"]);

// Supported image MIME types
const imageMimeTypes = [
"image/jpeg",
"image/png",
"image/gif",
"image/bmp",
"image/webp",
"image/svg+xml",
"image/tiff"
];

while (files.hasNext()) {
const file = files.next();
const mimeType = file.getMimeType();
Logger.log(mimeType);

// Check if the file is an image
if (imageMimeTypes.includes(mimeType)) {
const fileName = file.getName();
const fileUrl = file.getUrl();
const base64 = convertToBase64(file);
const longDescription = createDescription(base64, file.getMimeType());

// Add the file info to the spreadsheet
sheet.appendRow([fileName, fileUrl, mimeType, longDescription]);
}
}

Logger.log('File listing complete!');
}

/**
* Convert the file to a Base64 encoded string.
*/
function convertToBase64(file) {
const blob = file.getBlob();
const base64String = Utilities.base64Encode(blob.getBytes());
return base64String;
}

/**
* Call Gemini AI to generate an image description.
*/
function createDescription(base64, fileMimeType) {
try {
const text = `Provide a detailed long description in less than 255 characters for the image.`;
const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro-latest:generateContent?key=${GEMIKEY}`;

const inlineData = {
mimeType: fileMimeType,
data: base64,
};

// Make a POST request to the Gemini API
const response = UrlFetchApp.fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
payload: JSON.stringify({
contents: [{ parts: [{ inlineData }, { text }] }],
}),
});

const data = JSON.parse(response);
return data.candidates[0].content.parts[0].text.trim();
} catch (error) {
Logger.log('Error calling Gemini AI: ' + error);
return 'Failed to generate description';
}
}

πŸ“˜ How It Works

  1. List Image Files from Google Drive
    • Extracts file name, URL, and MIME type for all images in a folder.
  2. Convert Images to Base64
    • Converts images to Base64 to send them as inline data to Gemini AI.
  3. Call Gemini AI
    • Sends each image and a prompt to Gemini AI.
    • Returns a description of each image.
  4. Update Google Sheets
    • Lists each image file name, URL, MIME type, and AI-generated description in the Google Sheet.

πŸ“˜ Instructions for Use

1️⃣ Create a Google Drive Folder

  1. Create a folder in Google Drive and add image files (JPG, PNG, etc.) to it.
  2. Get the folder ID from the URL (the part after /folders/).

2️⃣ Create a Google Sheet

  1. Create a new Google Sheet.
  2. Rename the first sheet to list.
  3. Copy the Google Sheet ID from the URL (the part after /spreadsheets/d/).

3️⃣ Update the Script

  1. Replace the folder ID in this line: const IMAGEFOLDER = 'YOUR_FOLDER_ID_HERE';
  2. Replace the Google Sheet ID in this line: const SHEETID = 'YOUR_SHEET_ID_HERE';
  3. Replace the Gemini AI API key in this line: const GEMIKEY = 'YOUR_GEMINI_API_KEY_HERE';

4️⃣ Run the Script

  1. Open Google Apps Script.
  2. Run listFilesInFolder().
  3. Open the Google Sheet to see the file names, URLs, MIME types, and descriptions.

πŸ“˜ Example Output (Google Sheets)

File NameFile URLMIME TypeAI Description
nature.jpgLink to the fileimage/jpeg“A beautiful scenic view of a mountain range with a lake in the foreground.”
workspace.pngLink to the fileimage/png“A modern workspace with a laptop, coffee cup, and notebook on a desk.”
cat-photo.gifLink to the fileimage/gif“A playful cat chasing a toy in a well-lit living room.”

πŸ“˜ Customization Ideas

  • Add More File Types β€” Extend support to PDF, Word, or other file types.
  • Custom Descriptions β€” Customize the prompt sent to Gemini AI for more specific descriptions.
  • Add Image Preview β€” Use HYPERLINK() or IMAGE() formulas to display images in the Google Sheet.

πŸ“˜ Troubleshooting

IssueCauseSolution
No API KeyGemini API key missingAdd the Gemini API key to the script.
Folder Not FoundIncorrect folder IDEnsure you’re using the correct folder ID.
Error Calling Gemini AIAPI not enabledEnable Gemini API in Google Cloud.
Blank DescriptionsImage could not be processedCheck image file type and size.

πŸ“˜ Final Thoughts

This script allows you to:

  • List image files from a Google Drive folder.
  • Generate descriptions for images using Gemini AI.
  • Export details to Google Sheets for easy viewing.

With this tool, you can automate cataloging image assets, SEO optimization, and image annotation. The entire process is simple, fast, and efficient.