Genera imágenes con Gemini

Gemini 2.5 Flash Image admite la generación de respuestas en múltiples modalidades, incluidas imágenes y texto.

Generación de imágenes

Gemini 2.5 Flash Image (gemini-2.5-flash-image) admite la capacidad de generar imágenes además de texto. Esto amplía las capacidades de Gemini para incluir lo siguiente:

  • Genera imágenes de forma iterativa a través de conversaciones en lenguaje natural y ajusta las imágenes manteniendo la coherencia y el contexto.
  • Genera imágenes con renderización de texto largo de alta calidad.
  • Genera una salida intercalada de texto e imagen. Por ejemplo, una entrada de blog con texto e imágenes en un solo turno. Anteriormente, esto requería encadenar varios modelos.
  • Generar imágenes con el conocimiento del mundo y las capacidades de razonamiento de Gemini

Con este lanzamiento experimental público, Gemini 2.5 Flash Image puede generar imágenes en 1, 024 px, admite la generación de imágenes de personas y contiene filtros de seguridad actualizados que brindan una experiencia del usuario más flexible y menos restrictiva.

Admite las siguientes modalidades y capacidades:

  • Texto a imagen

    • Ejemplo de instrucción: "Genera una imagen de la Torre Eiffel con fuegos artificiales en el fondo".
  • Texto a imagen (renderización de texto)

    • Ejemplo de instrucción: "Genera una foto cinematográfica de un edificio grande con esta proyección de texto gigante asignada en el frente del edificio: "Gemini 2.5 ahora puede generar texto de formato largo"".
  • Texto a imagen(es) y texto (intercalado)

    • Ejemplo de instrucción: "Genera una receta ilustrada de paella. Crea imágenes junto con el texto a medida que generas la receta".
    • Ejemplo de instrucción: "Genera una historia sobre un perro en un estilo de animación de dibujos animados en 3D. Para cada escena, genera una imagen".
  • Imágenes y texto a imágenes y texto (intercalado)

    • Ejemplo de instrucción: (Con una imagen de una habitación amueblada) "¿Qué otros colores de sofás combinarían con mi espacio? ¿Puedes actualizar la imagen?"
  • Generación de imágenes con reconocimiento de configuración regional

    • Ejemplo de instrucción: "Genera una imagen de un desayuno".

Prácticas recomendadas

Para mejorar los resultados de la generación de imágenes, sigue estas prácticas recomendadas:

  • Sé específico: Cuantos más detalles brindes, más control tendrás. Por ejemplo, en lugar de "armadura de fantasía", prueba con "armadura de placas élfica ornamentada, grabada con patrones de hojas de plata, con un cuello alto y hombreras con forma de alas de halcón".

  • Proporciona contexto y la intención: Explica el propósito de la imagen para ayudar al modelo a comprender el contexto. Por ejemplo, "Crea un logotipo para una marca de cuidado de la piel minimalista y de alta gama" funciona mejor que "Crea un logotipo".

  • Itera y define mejor: No esperes obtener una imagen perfecta en el primer intento. Usa instrucciones de seguimiento para realizar pequeños cambios, por ejemplo, "Haz que la iluminación sea más cálida" o "Cambia la expresión del personaje para que sea más seria".

  • Usa instrucciones paso a paso: Para las escenas complejas, divide tu solicitud en pasos. Por ejemplo, "Primero, crea un fondo de un bosque sereno y brumoso al amanecer. Luego, en primer plano, agrega un antiguo altar de piedra cubierto de musgo. Por último, coloca una sola espada brillante sobre el altar".

  • Describe lo que quieres, no lo que no quieres: En lugar de decir "sin autos", describe la escena de forma positiva diciendo "una calle vacía y desierta sin señales de tráfico".

  • Controlar la cámara: Guía la vista de la cámara. Usa términos fotográficos y cinematográficos para describir la composición, por ejemplo, "toma de gran angular", "toma macro" o "perspectiva de ángulo bajo".

  • Instrucciones para generar imágenes: Describe la intención con frases como "crea una imagen de" o "genera una imagen de". De lo contrario, el modelo multimodal podría responder con texto en lugar de la imagen.

Limitaciones:

  • Para obtener el mejor rendimiento, usa los siguientes idiomas: EN, es-MX, ja-JP, zh-CN y hi-IN.

  • La generación de imágenes no admite entradas de audio ni video.

  • Es posible que el modelo no cree la cantidad exacta de imágenes que solicitaste.

  • Para obtener mejores resultados, incluye un máximo de tres imágenes en una entrada.

  • Cuando generes una imagen que contenga texto, primero genera el texto y, luego, genera una imagen con ese texto.

  • Es posible que la generación de imágenes o texto no funcione según lo esperado en las siguientes situaciones:

    • Es posible que el modelo solo cree texto. Si quieres imágenes, pídelas claramente en tu solicitud. Por ejemplo, "proporciona imágenes a medida que avanzas".

    • Es posible que el modelo cree texto como una imagen. Para generar texto, pide específicamente una salida de texto. Por ejemplo, "genera texto narrativo junto con ilustraciones".

    • El modelo podría dejar de generar contenido incluso cuando no haya terminado. Si esto ocurre, vuelve a intentarlo o usa una instrucción diferente.

    • Si una instrucción es potencialmente insegura, es posible que el modelo no procese la solicitud y muestre una respuesta que indique que no puede crear imágenes inseguras. En este caso, el FinishReason es STOP.

Generar imágenes

En las siguientes secciones, se explica cómo generar imágenes con Vertex AI Studio o la API.

Para obtener orientación y conocer las prácticas recomendadas para generar instrucciones, consulta Diseña instrucciones multimodales.

Console

Para usar la generación de imágenes, sigue estos pasos:

  1. Abre Vertex AI Studio > Crear instrucción.
  2. Haz clic en Cambiar modelo y selecciona gemini-2.5-flash-image en el menú.
  3. En el panel Salidas, selecciona Imagen y texto en el menú desplegable.
  4. Escribe una descripción de la imagen que quieres generar en el área de texto de Escribe una instrucción.
  5. Haz clic en el botón Instrucción ().

Gemini generará una imagen según tu descripción. Este proceso debería tardar unos segundos, pero puede ser comparativamente más lento según la capacidad.

Python

Instalar

pip install --upgrade google-genai

Para obtener más información, consulta la documentación de referencia del SDK.

Establece variables de entorno para usar el SDK de IA generativa con Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai
from google.genai.types import GenerateContentConfig, Modality
from PIL import Image
from io import BytesIO

client = genai.Client()

response = client.models.generate_content(
    model="gemini-2.5-flash-image",
    contents=("Generate an image of the Eiffel tower with fireworks in the background."),
    config=GenerateContentConfig(
        response_modalities=[Modality.TEXT, Modality.IMAGE],
        candidate_count=1,
        safety_settings=[
            {"method": "PROBABILITY"},
            {"category": "HARM_CATEGORY_DANGEROUS_CONTENT"},
            {"threshold": "BLOCK_MEDIUM_AND_ABOVE"},
        ],
    ),
)
for part in response.candidates[0].content.parts:
    if part.text:
        print(part.text)
    elif part.inline_data:
        image = Image.open(BytesIO((part.inline_data.data)))
        image.save("output_folder/example-image-eiffel-tower.png")
# Example response:
#   I will generate an image of the Eiffel Tower at night, with a vibrant display of
#   colorful fireworks exploding in the dark sky behind it. The tower will be
#   illuminated, standing tall as the focal point of the scene, with the bursts of
#   light from the fireworks creating a festive atmosphere.

Node.js

Instalar

npm install @google/genai

Para obtener más información, consulta la documentación de referencia del SDK.

Establece variables de entorno para usar el SDK de IA generativa con Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

const fs = require('fs');
const {GoogleGenAI, Modality} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION =
  process.env.GOOGLE_CLOUD_LOCATION || 'us-central1';

async function generateContent(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  const response = await client.models.generateContentStream({
    model: 'gemini-2.5-flash-image',
    contents:
      'Generate an image of the Eiffel tower with fireworks in the background.',
    config: {
      responseModalities: [Modality.TEXT, Modality.IMAGE],
    },
  });

  const generatedFileNames = [];
  let imageIndex = 0;
  for await (const chunk of response) {
    const text = chunk.text;
    const data = chunk.data;
    if (text) {
      console.debug(text);
    } else if (data) {
      const fileName = `generate_content_streaming_image_${imageIndex++}.png`;
      console.debug(`Writing response image to file: ${fileName}.`);
      try {
        fs.writeFileSync(fileName, data);
        generatedFileNames.push(fileName);
      } catch (error) {
        console.error(`Failed to write image file ${fileName}:`, error);
      }
    }
  }

  return generatedFileNames;
}

Java

Obtén más información para instalar o actualizar Java.

Para obtener más información, consulta la documentación de referencia del SDK.

Establece variables de entorno para usar el SDK de IA generativa con Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True


import com.google.genai.Client;
import com.google.genai.types.Blob;
import com.google.genai.types.Candidate;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.Part;
import com.google.genai.types.SafetySetting;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;

public class ImageGenMmFlashWithText {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-flash-image";
    String outputFile = "resources/output/example-image-eiffel-tower.png";
    generateContent(modelId, outputFile);
  }

  // Generates an image with text input
  public static void generateContent(String modelId, String outputFile) throws IOException {
    // Client Initialization. Once created, it can be reused for multiple requests.
    try (Client client = Client.builder().location("global").vertexAI(true).build()) {

      GenerateContentConfig contentConfig =
          GenerateContentConfig.builder()
              .responseModalities("TEXT", "IMAGE")
              .candidateCount(1)
              .safetySettings(
                  SafetySetting.builder()
                      .method("PROBABILITY")
                      .category("HARM_CATEGORY_DANGEROUS_CONTENT")
                      .threshold("BLOCK_MEDIUM_AND_ABOVE")
                      .build())
              .build();

      GenerateContentResponse response =
          client.models.generateContent(
              modelId,
              "Generate an image of the Eiffel tower with fireworks in the background.",
              contentConfig);

      // Get parts of the response
      List<Part> parts =
          response
              .candidates()
              .flatMap(candidates -> candidates.stream().findFirst())
              .flatMap(Candidate::content)
              .flatMap(Content::parts)
              .orElse(new ArrayList<>());

      // For each part print text if present, otherwise read image data if present and
      // write it to the output file
      for (Part part : parts) {
        if (part.text().isPresent()) {
          System.out.println(part.text().get());
        } else if (part.inlineData().flatMap(Blob::data).isPresent()) {
          BufferedImage image =
              ImageIO.read(new ByteArrayInputStream(part.inlineData().flatMap(Blob::data).get()));
          ImageIO.write(image, "png", new File(outputFile));
        }
      }

      System.out.println("Content written to: " + outputFile);
      // Example response:
      // Here is the Eiffel Tower with fireworks in the background...
      //
      // Content written to: resources/output/example-image-eiffel-tower.png
    }
  }
}

REST

Ejecuta el siguiente comando en la terminal para crear o reemplazar este archivo en el directorio actual:

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://${API_ENDPOINT}:generateContent \
  -d '{
    "contents": {
      "role": "USER",
      "parts": { "text": "Create a tutorial explaining how to make a peanut butter and jelly sandwich in three easy steps."},
    },
    "generation_config": {
      "response_modalities": ["TEXT", "IMAGE"],
      "image_config": {
        "aspect_ratio": "16:9",
      },
     },
     "safetySettings": {
      "method": "PROBABILITY",
      "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
  }' 2>/dev/null >response.json

Gemini generará una imagen según tu descripción. Este proceso debería tardar unos segundos, pero puede ser comparativamente más lento según la capacidad.

Genera imágenes y texto intercalado

Gemini 2.5 Flash Image puede generar imágenes intercaladas con sus respuestas de texto. Por ejemplo, puedes generar imágenes de cómo se vería cada paso de una receta generada para acompañar el texto de ese paso, sin tener que hacer solicitudes separadas al modelo para hacerlo.

Console

Para generar imágenes intercaladas con respuestas de texto, sigue estos pasos:

  1. Abre Vertex AI Studio > Crear instrucción.
  2. Haz clic en Cambiar modelo y selecciona gemini-2.5-flash-image en el menú.
  3. En el panel Salidas, selecciona Imagen y texto en el menú desplegable.
  4. Escribe una descripción de la imagen que quieres generar en el área de texto de Escribe una instrucción. Por ejemplo, "Crea un instructivo en el que se explique cómo preparar un sándwich de mantequilla de maní y mermelada en tres sencillos pasos. Para cada paso, proporciona un título con el número del paso, una explicación y también genera una imagen en una relación de aspecto de 1:1".
  5. Haz clic en el botón Instrucción ().

Gemini generará una respuesta basada en tu descripción. Este proceso debería tardar unos segundos, pero puede ser comparativamente más lento según la capacidad.

Python

Instalar

pip install --upgrade google-genai

Para obtener más información, consulta la documentación de referencia del SDK.

Establece variables de entorno para usar el SDK de IA generativa con Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai
from google.genai.types import GenerateContentConfig, Modality
from PIL import Image
from io import BytesIO

client = genai.Client()

response = client.models.generate_content(
    model="gemini-2.5-flash-image",
    contents=(
        "Generate an illustrated recipe for a paella."
        "Create images to go alongside the text as you generate the recipe"
    ),
    config=GenerateContentConfig(response_modalities=[Modality.TEXT, Modality.IMAGE]),
)
with open("output_folder/paella-recipe.md", "w") as fp:
    for i, part in enumerate(response.candidates[0].content.parts):
        if part.text is not None:
            fp.write(part.text)
        elif part.inline_data is not None:
            image = Image.open(BytesIO((part.inline_data.data)))
            image.save(f"output_folder/example-image-{i+1}.png")
            fp.write(f"![image](example-image-{i+1}.png)")
# Example response:
#  A markdown page for a Paella recipe(`paella-recipe.md`) has been generated.
#   It includes detailed steps and several images illustrating the cooking process.

Java

Obtén más información para instalar o actualizar Java.

Para obtener más información, consulta la documentación de referencia del SDK.

Establece variables de entorno para usar el SDK de IA generativa con Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True


import com.google.genai.Client;
import com.google.genai.types.Blob;
import com.google.genai.types.Candidate;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.Part;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;

public class ImageGenMmFlashTextAndImageWithText {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-flash-image";
    String outputFile = "resources/output/paella-recipe.md";
    generateContent(modelId, outputFile);
  }

  // Generates text and image with text input
  public static void generateContent(String modelId, String outputFile) throws IOException {
    // Client Initialization. Once created, it can be reused for multiple requests.
    try (Client client = Client.builder().location("global").vertexAI(true).build()) {

      GenerateContentResponse response =
          client.models.generateContent(
              modelId,
              Content.fromParts(
                  Part.fromText("Generate an illustrated recipe for a paella."),
                  Part.fromText(
                      "Create images to go alongside the text as you generate the recipe.")),
              GenerateContentConfig.builder().responseModalities("TEXT", "IMAGE").build());

      try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {

        // Get parts of the response
        List<Part> parts =
            response
                .candidates()
                .flatMap(candidates -> candidates.stream().findFirst())
                .flatMap(Candidate::content)
                .flatMap(Content::parts)
                .orElse(new ArrayList<>());

        int index = 1;
        // For each part print text if present, otherwise read image data if present and
        // write it to the output file
        for (Part part : parts) {
          if (part.text().isPresent()) {
            writer.write(part.text().get());
          } else if (part.inlineData().flatMap(Blob::data).isPresent()) {
            BufferedImage image =
                ImageIO.read(new ByteArrayInputStream(part.inlineData().flatMap(Blob::data).get()));
            ImageIO.write(
                image, "png", new File("resources/output/example-image-" + index + ".png"));
            writer.write("![image](example-image-" + index + ".png)");
          }
          index++;
        }

        System.out.println("Content written to: " + outputFile);

        // Example response:
        // A markdown page for a Paella recipe(`paella-recipe.md`) has been generated.
        // It includes detailed steps and several images illustrating the cooking process.
        //
        // Content written to:  resources/output/paella-recipe.md
      }
    }
  }
}

REST

Ejecuta el siguiente comando en la terminal para crear o reemplazar este archivo en el directorio actual:

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://${API_ENDPOINT}:generateContent \
  -d '{
    "contents": {
      "role": "USER",
      "parts": { "text": "Create a tutorial explaining how to make a peanut butter and jelly sandwich in three easy steps. For each step, provide a title with the number of the step, an explanation, and also generate an image, generate each image in a 1:1 aspect ratio."},
    },
    "generation_config": {
      "response_modalities": ["TEXT", "IMAGE"],
      "image_config": {
        "aspect_ratio": "16:9",
      },
    },
    "safetySettings": {
      "method": "PROBABILITY",
      "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
  }' 2>/dev/null >response.json

Gemini generará una imagen según tu descripción. Este proceso debería tardar unos segundos, pero puede ser comparativamente más lento según la capacidad.

Generación de imágenes con reconocimiento de configuración regional

Gemini 2.5 Flash Image también puede incluir información sobre tu ubicación cuando proporciona respuestas de texto o imágenes. Por ejemplo, puedes generar imágenes de tipos de ubicaciones o experiencias que tengan en cuenta tu ubicación actual sin tener que especificarla en el modelo.

Console

Para usar la generación de imágenes con reconocimiento de configuración regional, sigue estos pasos:

  1. Abre Vertex AI Studio > Crear instrucción.
  2. Haz clic en Cambiar modelo y selecciona gemini-2.5-flash-image en el menú.
  3. En el panel Salidas, selecciona Imagen y texto en el menú desplegable.
  4. Escribe una descripción de la imagen que quieres generar en el área de texto de Escribe una instrucción. Por ejemplo, "Genera una foto de un desayuno típico".
  5. Haz clic en el botón Instrucción ().

Gemini generará una respuesta basada en tu descripción. Este proceso debería tardar unos segundos, pero puede ser comparativamente más lento según la capacidad.

Python

Instalar

pip install --upgrade google-genai

Para obtener más información, consulta la documentación de referencia del SDK.

Establece variables de entorno para usar el SDK de IA generativa con Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai
from google.genai.types import GenerateContentConfig, Modality
from PIL import Image
from io import BytesIO

client = genai.Client()

response = client.models.generate_content(
    model="gemini-2.5-flash-image",
    contents=("Generate a photo of a breakfast meal."),
    config=GenerateContentConfig(response_modalities=[Modality.TEXT, Modality.IMAGE]),
)
for part in response.candidates[0].content.parts:
    if part.text:
        print(part.text)
    elif part.inline_data:
        image = Image.open(BytesIO((part.inline_data.data)))
        image.save("output_folder/example-breakfast-meal.png")
# Example response:
#   Generates a photo of a vibrant and appetizing breakfast meal.
#   The scene will feature a white plate with golden-brown pancakes
#   stacked neatly, drizzled with rich maple syrup and ...

Java

Obtén más información para instalar o actualizar Java.

Para obtener más información, consulta la documentación de referencia del SDK.

Establece variables de entorno para usar el SDK de IA generativa con Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True


import com.google.genai.Client;
import com.google.genai.types.Blob;
import com.google.genai.types.Candidate;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.Part;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;

public class ImageGenMmFlashLocaleAwareWithText {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-flash-image";
    String outputFile = "resources/output/example-breakfast-meal.png";
    generateContent(modelId, outputFile);
  }

  // Generates an image with text input
  public static void generateContent(String modelId, String outputFile) throws IOException {
    // Client Initialization. Once created, it can be reused for multiple requests.
    try (Client client = Client.builder().location("global").vertexAI(true).build()) {

      GenerateContentResponse response =
          client.models.generateContent(
              modelId,
              "Generate a photo of a breakfast meal.",
              GenerateContentConfig.builder().responseModalities("TEXT", "IMAGE").build());

      // Get parts of the response
      List<Part> parts =
          response
              .candidates()
              .flatMap(candidates -> candidates.stream().findFirst())
              .flatMap(Candidate::content)
              .flatMap(Content::parts)
              .orElse(new ArrayList<>());

      // For each part print text if present, otherwise read image data if present and
      // write it to the output file
      for (Part part : parts) {
        if (part.text().isPresent()) {
          System.out.println(part.text().get());
        } else if (part.inlineData().flatMap(Blob::data).isPresent()) {
          BufferedImage image =
              ImageIO.read(new ByteArrayInputStream(part.inlineData().flatMap(Blob::data).get()));
          ImageIO.write(image, "png", new File(outputFile));
        }
      }

      System.out.println("Content written to: " + outputFile);

      // Example response:
      // Here is a photo of a breakfast meal for you!
      //
      // Content written to: resources/output/example-breakfast-meal.png
    }
  }
}

REST

Ejecuta el siguiente comando en la terminal para crear o reemplazar este archivo en el directorio actual:

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://${API_ENDPOINT}:generateContent \
  -d '{
    "contents": {
      "role": "USER",
      "parts": { "text": "Generate a photo of a typical breakfast."},
    },
    "generation_config": {
      "response_modalities": ["TEXT", "IMAGE"],
      "image_config": {
        "aspect_ratio": "16:9",
      },
    },
    "safetySettings": {
      "method": "PROBABILITY",
      "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
  }' 2>/dev/null >response.json

Gemini generará una imagen según tu descripción. Este proceso debería tardar unos segundos, pero puede ser comparativamente más lento según la capacidad.