Automate AI Image Generation & Storage with n8n and Google

This workflow automates AI-driven image generation from chat prompts using OpenAI, then saves images to Google Drive and logs everything in Google Sheets. It solves time-consuming manual image creation and management tasks.
httpRequest
googleDrive
googleSheets
+8
Workflow Identifier: 1012
NODES in Use: manualTrigger, httpRequest, googleDrive, splitOut, convertToFile, splitInBatches, set, googleSheets, aggregate, chatTrigger, stickyNote

Press CTRL+F5 if the workflow didn't load.

Learn how to Build this Workflow with AI:

Visit through Desktop for Best experience

1. Opening Problem Statement

Darrell is an AI automation engineer who frequently experiments with generating images from text prompts using GPT’s image model. However, manually managing these images—downloading from APIs, uploading to cloud drive, and logging details into spreadsheets—consumes hours every week. Even occasional errors, like file naming mistakes or missed records, disrupt his workflow and slow down projects.

He wants a smooth automated solution that takes his chat-based image descriptions, generates images, stores them neatly on Google Drive, and captures all metadata including usage cost in Google Sheets. Without such automation, valuable time is wasted on repetitive manual tasks, leading to delays and lost productivity.

2. What This Automation Does

When you run this n8n workflow, here’s exactly what happens:

  • Chat prompt reception: A chat message with an image description triggers the workflow instantly.
  • AI image generation: Sends the prompt to OpenAI’s image generation API with specific parameters.
  • Image processing loop: Handles multiple returned images smoothly, converting base64 data into files.
  • Google Drive upload: Automatically creates a uniquely named folder and uploads images there.
  • Google Sheets logging: Logs image URLs, thumbnails, and prompts to a Sheet for easy tracking.
  • Usage cost tracking: Calculates and stores input/output token usage with estimated cost metrics in a separate usage sheet.

This saves Darrell several hours a week, eliminates manual errors, and centralizes all AI image generation data and files with minimal fuss.

3. Prerequisites ⚙️

  • n8n account (cloud or self-hosted) ⚙️
  • OpenAI API account with access to the GPT image generation model 🔑
  • Google Drive account with OAuth2 credentials set up 📁🔐
  • Google Sheets account with OAuth2 credentials and a pre-prepared spreadsheet 📊🔐

4. Step-by-Step Guide

Step 1: Set up a Chat Trigger node

Navigate to n8n Editor UI → Click + Node → Search for “Chat Trigger” (n8n-nodes-langchain.chatTrigger) → Drag it onto canvas. This node listens for chat messages to trigger your workflow.

Configure webhook settings if prompted. The trigger will fire when a chat message containing your image description arrives.

Expected outcome: The workflow will start on receiving chat input.

Common mistake: Forgetting to activate the webhook URL, causing the trigger not to fire.

Step 2: Add HTTP Request node to call OpenAI Image API

Add HTTP Request node (n8n-nodes-base.httpRequest) → Set method to POST

Enter URL: https://api.openai.com/v1/images/generations

Under Body Parameters, add:

  • model: gpt-image-1
  • prompt: Use expression {{ $json.chatInput }} to pass chat text
  • output_format: jpeg
  • quality: low
  • output_compression: {{parseInt('80')}}
  • size: 1024x1024
  • n: {{parseInt('1')}} (number of images)
  • moderation: low

Set authentication to your OpenAI API credentials.

Expected outcome: The OpenAI API returns image data for your prompt.

Common mistake: Missing or incorrect API key will cause authentication errors.

Step 3: Split the image data array

Add the Split Out node (n8n-nodes-base.splitOut) → Configure to split the data field with option to include binary data.

This prepares each image item in the array to be processed separately even if only one image.

Expected outcome: The images are separated into individual items.

Common mistake: Forgetting to specify the correct field to split results in processing errors.

Step 4: Loop through images one by one

Add Loop Over Items node (n8n-nodes-base.splitInBatches) → Set batch size to 1.

This processes each image sequentially (important when uploading files).

Expected outcome: One image is handled at a time.

Common mistake: Setting batch size too high may cause API limits or upload conflicts.

Step 5: Format file name fields

Add Edit Fields-file_name node (n8n-nodes-base.set) → Create a new field called file_name with timestamp value using expression {{ $now.format("yyyyMMddHHmmSSS") }}.

Keep b64_json with base64 data unchanged.

Expected outcome: Each file gets a unique timestamp name to avoid collisions on Drive.

Common mistake: Not formatting names uniquely can overwrite previous files.

Step 6: Convert base64 JSON to Binary File

Add Convert to File node (n8n-nodes-base.convertToFile) → Source Property: b64_json, Filename: use timestamp from previous node.

This converts the image string into an actual file format for uploading.

Expected outcome: You get a binary file ready to upload to Google Drive.

Common mistake: Wrong source property leads to empty or broken files.

Step 7: Upload image to Google Drive Folder

Add Google Drive node (n8n-nodes-base.googleDrive) → Set Drive to “My Drive” and specify a folder ID to upload all images to a specific folder.

Name each file dynamically like chatgpt_created_by_n8n_{{ $('HTTP Request').item.json.created }}.

Expected outcome: All generated images are uploaded to your Drive with clear timestamps.

Common mistake: Using wrong folder ID will scatter files or cause upload failure.

Step 8: Enrich upload response with metadata

Add Edit Fields1 node (n8n-nodes-base.set) → Map Google Drive response fields such as id, webViewLink, thumbnailLink, and add file_name from previous.

Expected outcome: Enhanced JSON with all relevant URLs and file info.

Common mistake: Forgetting to include the file_name means losing link between upload and metadata.

Step 9: Append image details to Google Sheets

Add Google Sheets node (n8n-nodes-base.googleSheets) → Append operation to your chosen Sheet name and document ID.

Map columns: prompt with chat input, image with webViewLink, and image_thumb using IMAGE() formula pointing to thumbnailLink.

Expected outcome: Each image and its prompt get recorded in your spreadsheet automatically.

Common mistake: Leaving incorrect sheet ID or mismatch in columns causes appending failure.

Step 10: Aggregate usage data for billing

Add Aggregate node (n8n-nodes-base.aggregate) → Collect all usage data from each image batch.

Expected outcome: Summarized token usage data ready for logging.

Common mistake: Not linking the aggregate node correctly stops usage recording.

Step 11: Log token usage and cost to Google Sheets

Add second Google Sheets1 node (n8n-nodes-base.googleSheets) → Append usage rows with columns for prompt, timestamps, input/output tokens, and estimated costs using expressions from the HTTP Request node’s response.

Expected outcome: Your spreadsheet automatically tracks AI API usage and cost estimates by prompt.

Common mistake: Errors in expressions or missing credentials prevent logging.

5. Customizations ✏️

  • Adjust image size and quality: In the HTTP Request node, change size (e.g., 512×512) or quality (e.g., medium) to balance speed and output.
  • Multiple image generation: Modify n in the HTTP Request node’s body params to generate several images per prompt.
  • Folder structure by date: Change Google Drive node folder name or ID dynamically using the current date for better organization.
  • Additional metadata fields in Google Sheets: Expand columns to capture more API response info like file IDs or creation date.
  • Email notification on image upload: Add a Gmail or SMTP node to send automatically generated emails with image links post-upload.

6. Troubleshooting 🔧

Problem: “Authentication failed” on HTTP Request node.
Cause: API key for OpenAI invalid or expired.
Solution: Go to n8n Credentials → Reauthenticate OpenAI API credentials with correct key.

Problem: Uploaded Google Drive files not visible.
Cause: Wrong folder ID or permissions.
Solution: Verify folder ID in Google Drive node matches exact folder accessible by your Google account.

Problem: Google Sheets append operation error.
Cause: Mismatched column names or sheet ID.
Solution: Confirm sheet name and column mapping in Google Sheets node match your actual spreadsheet.

7. Pre-Production Checklist ✅

  • Test Chat Trigger by sending a sample prompt.
  • Verify OpenAI image generation returns valid image data.
  • Check Google Drive uploads appear in the targeted folder with correct names.
  • Confirm Google Sheets logs images and usage costs accurately.
  • Backup your Google Sheets before extensive automation.

8. Deployment Guide

Activate the workflow in n8n by enabling the Chat Trigger node and saving your workflow.

Monitor for errors using n8n’s execution logs and adjust triggers or node settings as needed.

Optional: Setup webhook security or IP restrictions based on your environment.

9. FAQs

Q: Can I use a different image generation API?
A: Yes, replace the HTTP Request node’s URL and body with the new API’s specs, but you’ll need to adjust parsing logic accordingly.

Q: Does this workflow use a lot of OpenAI API credits?
A: Usage logs and cost calculation in the Sheet help monitor and control spend.

Q: Is it secure to store API keys here?
A: Use n8n’s credential management system for encrypted storage of keys.

10. Conclusion

By following this detailed guide, you built an automated AI image generation system using n8n, OpenAI, Google Drive, and Google Sheets. You’ve saved hours weekly by automating prompt input, image generation, file uploads, and logging, all with accurate usage cost tracking.

Next steps could include adding notifications for new images, expanding to other AI models, or linking with CRM systems to integrate AI-generated content directly into marketing workflows.

This workflow highlights how powerful and flexible n8n is for bridging AI capabilities with cloud storage and record keeping in a real-world engineering context.

Promoted by BULDRR AI

Related Workflows

Automate Viral UGC Video Creation Using n8n + Degaus (Beginner-Friendly Guide)

Learn how to automate viral UGC video creation using n8n, AI prompts, and Degaus. This beginner-friendly guide shows how to import, configure, and run the workflow without technical complexity.
Form Trigger
Google Sheets
Gmail
+37
Free

AI SEO Blog Writer Automation in n8n (Beginner Guide)

A complete beginner guide to building an AI-powered SEO blog writer automation using n8n.
AI Agent
Google Sheets
httpRequest
+5
Free

Automate CrowdStrike Alerts with VirusTotal, Jira & Slack

This workflow automates processing of CrowdStrike detections by enriching threat data via VirusTotal, creating Jira tickets for incident tracking, and notifying teams on Slack for quick response. Save hours daily by transforming complex threat data into actionable alerts effortlessly.
scheduleTrigger
httpRequest
jira
+5
Free

Automate Telegram Invoices to Notion with AI Summaries & Reports

Save hours on financial tracking by automating invoice extraction from Telegram photos to Notion using Google Gemini AI. This workflow extracts data, records transactions, and generates detailed spending reports with charts sent on schedule via Telegram.
lmChatGoogleGemini
telegramTrigger
notion
+9
Free

Automate Email Replies with n8n and AI-Powered Summarization

Save hours managing your inbox with this n8n workflow that uses IMAP email triggers, AI summarization, and vector search to draft concise replies requiring minimal review. Automate business email processing efficiently with AI guidance and Gmail integration.
emailReadImap
vectorStoreQdrant
emailSend
+12
Free

Automate Email Campaigns Using n8n with Gmail & Google Sheets

This n8n workflow automates personalized email outreach campaigns by integrating Gmail and Google Sheets, saving hours of manual follow-up work and reducing errors in email sequences. It ensures timely follow-ups based on previous email interactions, optimizing communication efficiency.
googleSheets
gmail
code
+5
Free