Pembuatan gambar dengan Gemini

Gemini dapat membuat dan memproses gambar secara percakapan. Anda dapat memberikan perintah kepada Gemini dengan teks, gambar, atau kombinasi keduanya untuk menyelesaikan berbagai tugas terkait gambar, seperti pembuatan dan pengeditan gambar. Semua gambar generatif menyertakan watermark SynthID.

Pembuatan gambar mungkin tidak tersedia di semua wilayah dan negara. Tinjau halaman Model Gemini kami untuk mengetahui informasi selengkapnya.

Pembuatan gambar (teks ke gambar)

Kode berikut menunjukkan cara membuat gambar berdasarkan perintah deskriptif. Anda harus menyertakan responseModalities: ["TEXT", "IMAGE"] dalam konfigurasi Anda. Output hanya gambar tidak didukung dengan model ini.

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()

JavaScript

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
Gambar babi terbang fantastis buatan AI
Gambar babi terbang fantastis yang dibuat AI

Pengeditan gambar (teks-dan-gambar-ke-gambar)

Untuk mengedit gambar, tambahkan gambar sebagai input. Contoh berikut menunjukkan cara mengupload gambar berenkode base64. Untuk beberapa gambar dan payload yang lebih besar, lihat bagian input gambar.

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()

JavaScript

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

Mode pembuatan gambar lainnya

Gemini mendukung mode interaksi gambar lainnya berdasarkan struktur dan konteks perintah, termasuk:

  • Teks ke gambar dan teks (disisipkan): Menghasilkan gambar dengan teks terkait.
    • Contoh perintah: "Buat resep paella dengan ilustrasi."
  • Gambar dan teks ke gambar dan teks (disisipkan): Menggunakan gambar dan teks input untuk membuat gambar dan teks baru yang terkait.
    • Contoh perintah: (Dengan gambar ruangan yang dilengkapi perabot) "Sofa warna apa lagi yang cocok untuk ruangan saya? Bisakah Anda memperbarui gambar ini?"
  • Pengeditan gambar multi-turn (chat): Terus buat / edit gambar secara percakapan.
    • Contoh perintah: [upload gambar mobil biru.] , "Ubah mobil ini menjadi mobil convertible.", "Sekarang ubah warnanya menjadi kuning."

Batasan

  • Untuk performa terbaik, gunakan bahasa berikut: EN, es-MX, ja-JP, zh-CN, hi-IN.
  • Pembuatan gambar tidak mendukung input audio atau video.
  • Pembuatan gambar mungkin tidak selalu dipicu:
    • Model hanya dapat menghasilkan teks. Coba minta output gambar secara eksplisit (misalnya, "buat gambar", "berikan gambar saat Anda melanjutkan", "perbarui gambar").
    • Model dapat berhenti menghasilkan output di tengah proses. Coba lagi atau coba perintah lain.
  • Saat membuat teks untuk gambar, Gemini akan berfungsi paling baik jika Anda membuat teks terlebih dahulu, lalu meminta gambar dengan teks tersebut.
  • Ada beberapa wilayah/negara tempat Pembuatan gambar tidak tersedia. Lihat Model untuk mengetahui informasi selengkapnya.

Kapan menggunakan Imagen

Selain menggunakan kemampuan pembuatan gambar bawaan Gemini, Anda juga dapat mengakses Imagen, model pembuatan gambar khusus kami, melalui Gemini API.

Pilih Gemini saat:

  • Anda memerlukan gambar yang relevan secara kontekstual yang memanfaatkan pengetahuan dan penalaran dunia.
  • Memadukan teks dan gambar dengan lancar sangatlah penting.
  • Anda menginginkan visual yang akurat disematkan dalam urutan teks yang panjang.
  • Anda ingin mengedit gambar secara percakapan sambil mempertahankan konteks.

Pilih Imagen jika:

  • Kualitas gambar, fotorealisme, detail artistik, atau gaya tertentu (misalnya, impresionisme, anime) adalah prioritas utama.
  • Melakukan tugas pengeditan khusus seperti pembaruan latar belakang produk atau peningkatan kualitas gambar.
  • Menyuntikkan branding, gaya, atau membuat logo dan desain produk.

Imagen 4 harus menjadi model pilihan Anda untuk mulai membuat gambar dengan Imagen. Pilih Imagen 4 Ultra untuk kasus penggunaan lanjutan atau saat Anda memerlukan kualitas gambar terbaik. Perhatikan bahwa Imagen 4 Ultra hanya dapat membuat satu gambar dalam satu waktu.

Langkah berikutnya