π 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
- List Image Files from a Google Drive Folder
- Convert Images to Base64 β Send images to Gemini AI.
- Generate Descriptions Using Gemini AI β Get a detailed description of each image.
- Export Image Details to Google Sheets β List file name, URL, MIME type, and AI-generated descriptions.
π Prerequisites
- Google Drive Folder β Create a folder where your image files are stored.
- Google Sheet β Create a Google Sheet with a sheet named list.
- 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
- List Image Files from Google Drive
- Extracts file name, URL, and MIME type for all images in a folder.
- Convert Images to Base64
- Converts images to Base64 to send them as inline data to Gemini AI.
- Call Gemini AI
- Sends each image and a prompt to Gemini AI.
- Returns a description of each image.
- 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
- Create a folder in Google Drive and add image files (JPG, PNG, etc.) to it.
- Get the folder ID from the URL (the part after
/folders/
).
2οΈβ£ Create a Google Sheet
- Create a new Google Sheet.
- Rename the first sheet to list.
- Copy the Google Sheet ID from the URL (the part after
/spreadsheets/d/
).
3οΈβ£ Update the Script
- Replace the folder ID in this line:
const IMAGEFOLDER = 'YOUR_FOLDER_ID_HERE';
- Replace the Google Sheet ID in this line:
const SHEETID = 'YOUR_SHEET_ID_HERE';
- Replace the Gemini AI API key in this line: c
onst GEMIKEY = 'YOUR_GEMINI_API_KEY_HERE';
4οΈβ£ Run the Script
- Open Google Apps Script.
- Run listFilesInFolder().
- Open the Google Sheet to see the file names, URLs, MIME types, and descriptions.
π Example Output (Google Sheets)
File Name | File URL | MIME Type | AI Description |
---|---|---|---|
nature.jpg | Link to the file | image/jpeg | “A beautiful scenic view of a mountain range with a lake in the foreground.” |
workspace.png | Link to the file | image/png | “A modern workspace with a laptop, coffee cup, and notebook on a desk.” |
cat-photo.gif | Link to the file | image/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
Issue | Cause | Solution |
---|---|---|
No API Key | Gemini API key missing | Add the Gemini API key to the script. |
Folder Not Found | Incorrect folder ID | Ensure youβre using the correct folder ID. |
Error Calling Gemini AI | API not enabled | Enable Gemini API in Google Cloud. |
Blank Descriptions | Image could not be processed | Check 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.
