Gemini를 사용한 이미지 생성

Gemini는 대화형으로 이미지를 생성하고 처리할 수 있습니다. 텍스트, 이미지 또는 둘 다를 조합해 Gemini에 프롬프트를 제공하여 이미지 생성 및 수정과 같은 다양한 이미지 관련 작업을 실행할 수 있습니다. 생성된 모든 이미지에는 SynthID 워터마크가 포함됩니다.

일부 지역 및 국가에서는 이미지 생성 기능을 사용하지 못할 수 있습니다. 자세한 내용은 Gemini 모델 페이지를 참고하세요.

이미지 생성 (텍스트 이미지 변환)

다음 코드는 설명 프롬프트에 따라 이미지를 생성하는 방법을 보여줍니다. 구성에는 responseModalities: ["TEXT", "IMAGE"]이 포함되어야 합니다. 이러한 모델에서는 이미지 전용 출력이 지원되지 않습니다.

Python

from google import genai
from google.genai import types
from PIL import Image
from io import BytesIO
import base64

client = genai.Client()

contents = ('Hi, can you create a 3d rendered image of a pig '
            'with wings and a top hat flying over a happy '
            'futuristic scifi city with lots of greenery?')

response = client.models.generate_content(
    model="gemini-2.0-flash-preview-image-generation",
    contents=contents,
    config=types.GenerateContentConfig(
      response_modalities=['TEXT', 'IMAGE']
    )
)

for part in response.candidates[0].content.parts:
  if part.text is not None:
    print(part.text)
  elif part.inline_data is not None:
    image = Image.open(BytesIO((part.inline_data.data)))
    image.save('gemini-native-image.png')
    image.show()

자바스크립트

import { GoogleGenAI, Modality } from "@google/genai";
import * as fs from "node:fs";

async function main() {

  const ai = new GoogleGenAI({});

  const contents =
    "Hi, can you create a 3d rendered image of a pig " +
    "with wings and a top hat flying over a happy " +
    "futuristic scifi city with lots of greenery?";

  // Set responseModalities to include "Image" so the model can generate  an image
  const response = await ai.models.generateContent({
    model: "gemini-2.0-flash-preview-image-generation",
    contents: contents,
    config: {
      responseModalities: [Modality.TEXT, Modality.IMAGE],
    },
  });
  for (const part of response.candidates[0].content.parts) {
    // Based on the part type, either show the text or save the image
    if (part.text) {
      console.log(part.text);
    } else if (part.inlineData) {
      const imageData = part.inlineData.data;
      const buffer = Buffer.from(imageData, "base64");
      fs.writeFileSync("gemini-native-image.png", buffer);
      console.log("Image saved as gemini-native-image.png");
    }
  }
}

main();

Go

package main

import (
  "context"
  "fmt"
  "os"
  "google.golang.org/genai"
)

func main() {

  ctx := context.Background()
  client, err := genai.NewClient(ctx, nil)
  if err != nil {
      log.Fatal(err)
  }

  config := &genai.GenerateContentConfig{
      ResponseModalities: []string{"TEXT", "IMAGE"},
  }

  result, _ := client.Models.GenerateContent(
      ctx,
      "gemini-2.0-flash-preview-image-generation",
      genai.Text("Hi, can you create a 3d rendered image of a pig " +
                 "with wings and a top hat flying over a happy " +
                 "futuristic scifi city with lots of greenery?"),
      config,
  )

  for _, part := range result.Candidates[0].Content.Parts {
      if part.Text != "" {
          fmt.Println(part.Text)
      } else if part.InlineData != nil {
          imageBytes := part.InlineData.Data
          outputFilename := "gemini_generated_image.png"
          _ = os.WriteFile(outputFilename, imageBytes, 0644)
      }
  }
}

REST

curl -s -X POST
  "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-preview-image-generation:generateContent" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [{
      "parts": [
        {"text": "Hi, can you create a 3d rendered image of a pig with wings and a top hat flying over a happy futuristic scifi city with lots of greenery?"}
      ]
    }],
    "generationConfig":{"responseModalities":["TEXT","IMAGE"]}
  }' \
  | grep -o '"data": "[^"]*"' \
  | cut -d'"' -f4 \
  | base64 --decode > gemini-native-image.png
환상적인 날아다니는 돼지의 AI 생성 이미지
환상적인 날아다니는 돼지의 AI 생성 이미지

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

이미지 편집을 실행하려면 이미지를 입력으로 추가합니다. 다음 예에서는 base64로 인코딩된 이미지를 업로드하는 방법을 보여줍니다. 여러 이미지와 더 큰 페이로드의 경우 이미지 입력 섹션을 확인하세요.

Python

from google import genai
from google.genai import types
from PIL import Image
from io import BytesIO

import PIL.Image

image = PIL.Image.open('/path/to/image.png')

client = genai.Client()

text_input = ('Hi, This is a picture of me.'
            'Can you add a llama next to me?',)

response = client.models.generate_content(
    model="gemini-2.0-flash-preview-image-generation",
    contents=[text_input, image],
    config=types.GenerateContentConfig(
      response_modalities=['TEXT', 'IMAGE']
    )
)

for part in response.candidates[0].content.parts:
  if part.text is not None:
    print(part.text)
  elif part.inline_data is not None:
    image = Image.open(BytesIO((part.inline_data.data)))
    image.show()

자바스크립트

import { GoogleGenAI, Modality } from "@google/genai";
import * as fs from "node:fs";

async function main() {

  const ai = new GoogleGenAI({});

  // Load the image from the local file system
  const imagePath = "path/to/image.png";
  const imageData = fs.readFileSync(imagePath);
  const base64Image = imageData.toString("base64");

  // Prepare the content parts
  const contents = [
    { text: "Can you add a llama next to the image?" },
    {
      inlineData: {
        mimeType: "image/png",
        data: base64Image,
      },
    },
  ];

  // Set responseModalities to include "Image" so the model can generate an image
  const response = await ai.models.generateContent({
    model: "gemini-2.0-flash-preview-image-generation",
    contents: contents,
    config: {
      responseModalities: [Modality.TEXT, Modality.IMAGE],
    },
  });
  for (const part of response.candidates[0].content.parts) {
    // Based on the part type, either show the text or save the image
    if (part.text) {
      console.log(part.text);
    } else if (part.inlineData) {
      const imageData = part.inlineData.data;
      const buffer = Buffer.from(imageData, "base64");
      fs.writeFileSync("gemini-native-image.png", buffer);
      console.log("Image saved as gemini-native-image.png");
    }
  }
}

main();

Go

package main

import (
 "context"
 "fmt"
 "os"
 "google.golang.org/genai"
)

func main() {

 ctx := context.Background()
 client, err := genai.NewClient(ctx, nil)
 if err != nil {
     log.Fatal(err)
 }

 imagePath := "/path/to/image.png"
 imgData, _ := os.ReadFile(imagePath)

 parts := []*genai.Part{
   genai.NewPartFromText("Hi, This is a picture of me. Can you add a llama next to me?"),
   &genai.Part{
     InlineData: &genai.Blob{
       MIMEType: "image/png",
       Data:     imgData,
     },
   },
 }

 contents := []*genai.Content{
   genai.NewContentFromParts(parts, genai.RoleUser),
 }

 config := &genai.GenerateContentConfig{
     ResponseModalities: []string{"TEXT", "IMAGE"},
 }

 result, _ := client.Models.GenerateContent(
     ctx,
     "gemini-2.0-flash-preview-image-generation",
     contents,
     config,
 )

 for _, part := range result.Candidates[0].Content.Parts {
     if part.Text != "" {
         fmt.Println(part.Text)
     } else if part.InlineData != nil {
         imageBytes := part.InlineData.Data
         outputFilename := "gemini_generated_image.png"
         _ = os.WriteFile(outputFilename, imageBytes, 0644)
     }
 }
}

REST

IMG_PATH=/path/to/your/image1.jpeg

if [[ "$(base64 --version 2>&1)" = *"FreeBSD"* ]]; then
  B64FLAGS="--input"
else
  B64FLAGS="-w0"
fi

IMG_BASE64=$(base64 "$B64FLAGS" "$IMG_PATH" 2>&1)

curl -X POST \
  "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-preview-image-generation:generateContent" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d "{
      \"contents\": [{
        \"parts\":[
            {\"text\": \"'Hi, This is a picture of me. Can you add a llama next to me\"},
            {
              \"inline_data\": {
                \"mime_type\":\"image/jpeg\",
                \"data\": \"$IMG_BASE64\"
              }
            }
        ]
      }],
      \"generationConfig\": {\"responseModalities\": [\"TEXT\", \"IMAGE\"]}
    }"  \
  | grep -o '"data": "[^"]*"' \
  | cut -d'"' -f4 \
  | base64 --decode > gemini-edited-image.png

기타 이미지 생성 모드

Gemini는 프롬프트 구조와 컨텍스트에 따라 다음과 같은 다른 이미지 상호작용 모드를 지원합니다.

  • 텍스트 이미지 변환 및 텍스트(인터리브 처리): 관련 텍스트와 함께 이미지를 출력합니다.
    • 프롬프트 예시: '파에야에 관한 그림이 있는 레시피를 생성해 줘.'
  • 이미지 및 텍스트 이미지 변환 및 텍스트(인터리브 처리): 입력 이미지와 텍스트를 사용하여 새로운 관련 이미지와 텍스트를 만듭니다.
    • 프롬프트 예시: (가구가 완비된 방의 이미지 포함) "내 공간에 어떤 색상의 소파가 어울릴까? 이미지를 업데이트해 줘."
  • 멀티턴 이미지 편집 (채팅): 대화형으로 이미지를 계속 생성 / 편집합니다.
    • 프롬프트 예시: [파란색 자동차 이미지를 업로드하세요.] , '이 차를 컨버터블로 바꿔 줘.', '이제 색상을 노란색으로 바꿔 줘.'

제한사항

  • 최상의 성능을 위해 다음 언어를 사용하세요. EN, es-MX, ja-JP, zh-CN, hi-IN
  • 이미지 생성은 오디오 또는 동영상 입력을 지원하지 않습니다.
  • 이미지 생성이 항상 트리거되지는 않을 수 있습니다.
    • 모델은 텍스트만 출력할 수도 있습니다. 이미지 출력을 명시적으로 요청해 보세요(예: '이미지를 생성해 줘', '진행하면서 이미지를 제공해 줘', '이미지를 업데이트해 줘').
    • 모델이 생성을 중단할 수 있습니다. 다시 시도하거나 다른 프롬프트를 사용해 보세요.
  • 이미지에 대한 텍스트를 생성할 때 먼저 텍스트를 생성한 다음 텍스트와 함께 이미지를 요청하면 Gemini가 가장 잘 작동합니다.
  • 이미지 생성을 사용할 수 없는 지역/국가가 있습니다. 자세한 내용은 모델을 참고하세요.

Imagen을 사용해야 하는 경우

Gemini의 내장 이미지 생성 기능을 사용하는 것 외에도 Gemini API를 통해 Google의 전문 이미지 생성 모델인 Imagen에 액세스할 수 있습니다.

다음과 같은 경우 Gemini를 선택하세요.

  • 세계 지식과 추론을 활용하는 맥락상 관련성이 높은 이미지가 필요합니다.
  • 텍스트와 이미지를 매끄럽게 혼합하는 것이 중요합니다.
  • 긴 텍스트 시퀀스에 정확한 시각적 요소를 삽입하고 싶습니다.
  • 맥락을 유지하면서 대화형으로 이미지를 수정하고 싶습니다.

다음과 같은 경우 Imagen을 선택하세요.

  • 이미지 품질, 사실성, 예술적 디테일 또는 특정 스타일 (예: 인상주의, 애니메이션)이 최우선입니다.
  • 제품 배경 업데이트 또는 이미지 확대와 같은 전문적인 수정 작업을 수행합니다.
  • 브랜딩, 스타일을 주입하거나 로고 및 제품 디자인을 생성합니다.

Imagen 4는 Imagen으로 이미지를 생성할 때 기본 모델로 사용해야 합니다. 고급 사용 사례에 사용하거나 최고의 이미지 품질이 필요한 경우 Imagen 4 Ultra를 선택하세요. Imagen 4 Ultra는 한 번에 하나의 이미지만 생성할 수 있습니다.

다음 단계