Gemini로 이미지 수정하기

Gemini 2.5 Flash Image는 다양한 유형의 이미지 수정을 지원합니다.

이미지 수정

이미지 생성을 위한 Gemini 2.5 Flash Image(gemini-2.5-flash-image)는 이미지 생성 외에도 수정 기능을 지원합니다. Gemini 2.5 Flash Image는 이미지의 개선된 수정 및 멀티턴 수정을 지원하며, 더 유연하고 제한이 적은 사용자 환경을 제공하는 업데이트된 안전 필터를 포함합니다.

다음과 같은 형식과 기능을 지원합니다.

  • 이미지 편집(텍스트 및 이미지 간)

    • 프롬프트 예시: '이 이미지를 만화처럼 보이도록 수정해 줘.'
    • 프롬프트 예시: [고양이 이미지] + [베개 이미지] + '이 베개에 내 고양이 십자수를 만들어 줘.'
  • 멀티턴 이미지 편집(채팅)

    • 프롬프트 예시: [파란색 자동차 이미지를 업로드하세요.] '이 차를 컨버터블로 바꿔 줘.' '이제 색상을 노란색으로 바꿔 줘.' '스포일러를 추가해 줘.'

이미지 수정

콘솔

이미지를 수정하려면 다음 단계를 따르세요.

  1. Vertex AI Studio > 프롬프트 만들기를 엽니다.
  2. 모델 전환을 클릭하고 메뉴에서 gemini-2.5-flash-image를 선택합니다.
  3. 출력 패널의 드롭다운 메뉴에서 이미지 및 텍스트를 선택합니다.
  4. 미디어 삽입()을 클릭하고 메뉴에서 소스를 선택한 다음 대화상자의 안내를 따릅니다.
  5. 프롬프트 작성 텍스트 영역에 이미지에 적용할 수정사항을 작성합니다.
  6. 프롬프트() 버튼을 클릭합니다.

Gemini가 설명을 기반으로 제공된 이미지를 수정한 버전을 생성합니다. 이 프로세스는 몇 초 정도 걸리지만 용량에 따라 비교적 느릴 수 있습니다.

Python

설치

pip install --upgrade google-genai

자세한 내용은 SDK 참고 문서를 참조하세요.

Vertex AI에서 생성형 AI SDK를 사용하도록 환경 변수를 설정합니다.

# 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

Java를 설치하거나 업데이트하는 방법을 알아보세요.

자세한 내용은 SDK 참고 문서를 참조하세요.

Vertex AI에서 생성형 AI SDK를 사용하도록 환경 변수를 설정합니다.

# 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

터미널에서 다음 명령어를 실행하여 현재 디렉터리에 이 파일을 만들거나 덮어씁니다.

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

Gemini가 설명을 기반으로 이미지를 생성합니다. 이 프로세스는 몇 초 정도 걸리지만 용량에 따라 비교적 느릴 수 있습니다.

멀티턴 이미지 수정

Gemini 2.5 Flash Image는 개선된 멀티턴 수정도 지원하므로 수정된 이미지 응답을 받은 후 변경사항을 적용하여 모델에 응답할 수 있습니다. 이렇게 하면 대화형으로 이미지를 계속 수정할 수 있습니다.

전체 요청 파일 크기는 최대 50MB로 제한하는 것이 좋습니다.

멀티턴 이미지 수정을 테스트하려면 Gemini 2.5 Flash Image 노트북을 사용해 보세요.