Editar imagens com o Gemini

O Gemini 2.5 Flash Image é compatível com vários tipos de edição de imagens.

Edição de imagens

O Gemini 2.5 Flash Image para geração de imagens (gemini-2.5-flash-image) permite editar imagens além de gerá-las. O Gemini 2.5 Flash Image oferece suporte a edição aprimorada de imagens e edição em várias etapas, além de filtros de segurança atualizados que proporcionam uma experiência do usuário mais flexível e menos restritiva.

Ele é compatível com as seguintes modalidades e recursos:

  • Edição de imagens (texto e imagem para imagem)

    • Comando de exemplo: "Edite esta imagem para que ela pareça um desenho animado"
    • Exemplo de comando: [imagem de um gato] + [imagem de um travesseiro] + "Crie um ponto cruz do meu gato neste travesseiro".
  • Edição de imagens com várias interações (chat)

    • Exemplos de comandos: [faça upload de uma imagem de um carro azul.] "Transforme este carro em um conversível." "Agora mude a cor para amarelo." "Adicionar um spoiler."

Editar uma imagem

Console

Para editar imagens:

  1. Abra Vertex AI Studio > Criar comando.
  2. Clique em Trocar modelo e selecione gemini-2.5-flash-image no menu.
  3. No painel Saídas, selecione Imagem e texto no menu suspenso.
  4. Clique em Inserir mídia () e selecione uma origem no menu. Depois, siga as instruções da caixa de diálogo.
  5. Escreva as edições que você quer fazer na imagem na área de texto Escreva um comando.
  6. Clique no botão Comando ().

O Gemini vai gerar uma versão editada da imagem fornecida com base na sua descrição. Esse processo leva alguns segundos, mas pode ser mais lento dependendo da capacidade.

Python

Instalar

pip install --upgrade google-genai

Para saber mais, consulte a documentação de referência do SDK.

Defina variáveis de ambiente para usar o SDK de IA generativa com a 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()

# Using an image of Eiffel tower, with fireworks in the background.
image = Image.open("test_resources/example-image-eiffel-tower.png")

response = client.models.generate_content(
    model="gemini-2.5-flash-image",
    contents=[image, "Edit this image to make it look like a cartoon."],
    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/bw-example-image.png")
# Example response:
#  Here's the cartoon-style edit of the image:
#  Cartoon-style edit:
#  - Simplified the Eiffel Tower with bolder lines and slightly exaggerated proportions.
#  - Brightened and saturated the colors of the sky, fireworks, and foliage for a more vibrant, cartoonish look.
#  ....

Java

Saiba como instalar ou atualizar o Java.

Para saber mais, consulte a documentação de referência do SDK.

Defina variáveis de ambiente para usar o SDK de IA generativa com a 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.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;

public class ImageGenMmFlashEditImageWithTextAndImage {

  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/bw-example-image.png";
    generateContent(modelId, outputFile);
  }

  // Edits an image with image and 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()) {

      byte[] localImageBytes =
          Files.readAllBytes(Paths.get("resources/example-image-eiffel-tower.png"));

      GenerateContentResponse response =
          client.models.generateContent(
              modelId,
              Content.fromParts(
                  Part.fromBytes(localImageBytes, "image/png"),
                  Part.fromText("Edit this image to make it look like a cartoon.")),
              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:
      // No problem! Here's the image in a cartoon style...
      //
      // Content written to: resources/output/bw-example-image.png
    }
  }
}

REST

Execute o comando a seguir no terminal para criar ou substituir esse arquivo no diretório atual:

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": [
        {"file_data": {
          "mime_type": "image/jpg",
          "file_uri": "<var>FILE_NAME</var>"
          }
        },
        {"text": "Convert this photo to black and white, in a cartoonish style."},
      ]

    },
    "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

O Gemini vai gerar uma imagem com base na sua descrição. Esse processo leva alguns segundos, mas pode ser comparativamente mais lento dependendo da capacidade.

Edição de imagens com várias interações

O Gemini 2.5 Flash Image também oferece suporte a edição com vários turnos aprimorada, permitindo que você responda ao modelo com mudanças depois de receber uma resposta de imagem editada. Assim, você poderá continuar fazendo edições na imagem de forma conversacional.

Recomendamos limitar o tamanho total do arquivo de solicitação a 50 MB.

Para testar a edição de imagens em várias etapas, use o notebook do Gemini 2.5 Flash Image.