Generate Images with Gemini API using Google Apps Script

Gists

Description

Recently, image generation was supported in the Gemini API using Gemini 2.0 Flash Experimental and Imagen 3. This report introduces simple sample scripts for generating images using the Gemini API with Google Apps Script. When images can be created using the Gemini API with Google Apps Script, Google Apps Script, which seamlessly integrates with Google Docs, Sheets, and Slides, becomes a powerful tool for creating and managing them, and the applications are infinite.

Usage

1. Get API key

In order to use the scripts in this report, please use your API key. Ref This API key is used to use Gemini API.

2. Google Apps Script project

Please create a Google Apps Script project. You can use the standalone script type and the container-bound script type. Ref

3. Sample scripts

Sample 1

Please copy and paste the following script to the script editor of Google Apps Script project and set your API key and save the script.

function sample1() {
  const apiKey = "###"; // Please set your API key.

  const prompt = "Create an image of an apple.";

  const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp:generateContent?key=${apiKey}`;
  const payload = {
    contents: [{ parts: [{ text: prompt }], role: "user" }],
    generationConfig: { responseModalities: ["TEXT", "IMAGE"] },
  };
  const options = {
    payload: JSON.stringify(payload),
    contentType: "application/json",
    muteHttpExceptions: true,
  };
  const res = UrlFetchApp.fetch(url, options);

  const obj = JSON.parse(res.getContentText());
  const imageObj = obj.candidates[0].content.parts.find((e) => e.inlineData);
  const imageBlob = Utilities.newBlob(
    Utilities.base64Decode(imageObj.inlineData.data),
    imageObj.inlineData.mimeType
  );
  DriveApp.createFile(imageBlob.setName("sample"));
}

Sample 2

I have created GeminiWithFiles of a Google Apps Script library for using Gemini API. Ref When you use this library, please install it to your Google Apps Script project. Ref

function sample2() {
  const apiKey = "###"; // Please set your API key.

  const q = "Create an image of an apple.";
  const g = new GeminiWithFiles.geminiWithFiles({
    apiKey,
    exportRawData: true,
    model: "models/gemini-2.0-flash-exp",
    generationConfig: { responseModalities: ["TEXT", "IMAGE"] },
  });
  const res = g.generateContent({ q });

  const imageObj = res.candidates[0].content.parts.find((e) => e.inlineData);
  const imageBlob = Utilities.newBlob(
    Utilities.base64Decode(imageObj.inlineData.data),
    imageObj.inlineData.mimeType
  );
  DriveApp.createFile(imageBlob.setName("sample"));
}

4 Testing

When the above scripts are run, the following image is created in the root folder of your Google Drive.

Reference

 Share!