Tạo hình ảnh bằng Gemini (còn gọi là Nano Banana)

Gemini có thể tạo và xử lý hình ảnh theo cách trò chuyện. Bạn có thể đưa ra câu lệnh cho Gemini bằng văn bản, hình ảnh hoặc kết hợp cả hai. Nhờ đó, bạn có thể tạo, chỉnh sửa và lặp lại các hình ảnh một cách hiệu quả chưa từng có:

  • Text-to-Image: Tạo hình ảnh chất lượng cao từ nội dung mô tả bằng văn bản đơn giản hoặc phức tạp.
  • Hình ảnh + Văn bản sang hình ảnh (Chỉnh sửa): Cung cấp một hình ảnh và sử dụng câu lệnh dạng văn bản để thêm, xoá hoặc sửa đổi các phần tử, thay đổi kiểu hoặc điều chỉnh việc phân loại màu.
  • Nhiều hình ảnh thành một hình ảnh (Bố cục và chuyển kiểu): Sử dụng nhiều hình ảnh đầu vào để tạo một cảnh mới hoặc chuyển kiểu từ hình ảnh này sang hình ảnh khác.
  • Tinh chỉnh lặp đi lặp lại: Tham gia vào một cuộc trò chuyện để tinh chỉnh dần hình ảnh của bạn qua nhiều lượt, thực hiện các điều chỉnh nhỏ cho đến khi hình ảnh hoàn hảo.
  • Kết xuất văn bản có độ chân thực cao: Tạo hình ảnh chính xác có chứa văn bản dễ đọc và được đặt đúng vị trí, phù hợp với biểu trưng, sơ đồ và áp phích.

Tất cả hình ảnh được tạo đều có hình mờ SynthID.

Tạo hình ảnh (chuyển văn bản thành hình ảnh)

Đoạn mã sau đây minh hoạ cách tạo hình ảnh dựa trên một câu lệnh mô tả.

Python

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

client = genai.Client()

prompt = (
    "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"
)

response = client.models.generate_content(
    model="gemini-2.5-flash-image-preview",
    contents=[prompt],
)

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("generated_image.png")

JavaScript

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

async function main() {

  const ai = new GoogleGenAI({});

  const prompt =
    "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme";

  const response = await ai.models.generateContent({
    model: "gemini-2.5-flash-image-preview",
    contents: prompt,
  });
  for (const part of response.candidates[0].content.parts) {
    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)
  }

  result, _ := client.Models.GenerateContent(
      ctx,
      "gemini-2.5-flash-image-preview",
      genai.Text("Create a picture of a nano banana dish in a " +
                 " fancy restaurant with a Gemini theme"),
  )

  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.5-flash-image-preview:generateContent" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [{
      "parts": [
        {"text": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"}
      ]
    }]
  }' \
  | grep -o '"data": "[^"]*"' \
  | cut -d'"' -f4 \
  | base64 --decode > gemini-native-image.png
Hình ảnh do AI tạo về món ăn từ chuối siêu nhỏ
Hình ảnh do AI tạo về một món ăn làm từ chuối siêu nhỏ trong một nhà hàng theo chủ đề Gemini

Chỉnh sửa hình ảnh (chuyển văn bản và hình ảnh thành hình ảnh)

Lời nhắc: Hãy đảm bảo rằng bạn có các quyền cần thiết đối với mọi hình ảnh mà bạn tải lên. Đừng tạo nội dung vi phạm quyền của người khác, kể cả video hoặc hình ảnh lừa gạt, quấy rối hoặc gây hại. Khi sử dụng dịch vụ AI tạo sinh này, bạn phải tuân theo Chính sách về các hành vi bị cấm khi sử dụng của chúng tôi.

Ví dụ sau đây minh hoạ việc tải hình ảnh được mã hoá base64 lên. Đối với nhiều hình ảnh, tải trọng lớn hơn và các loại MIME được hỗ trợ, hãy xem trang Hiểu hình ảnh.

Python

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

client = genai.Client()

prompt = (
    "Create a picture of my cat eating a nano-banana in a "
    "fancy restaurant under the Gemini constellation",
)

image = Image.open("/path/to/cat_image.png")

response = client.models.generate_content(
    model="gemini-2.5-flash-image-preview",
    contents=[prompt, 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("generated_image.png")

JavaScript

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

async function main() {

  const ai = new GoogleGenAI({});

  const imagePath = "path/to/cat_image.png";
  const imageData = fs.readFileSync(imagePath);
  const base64Image = imageData.toString("base64");

  const prompt = [
    { text: "Create a picture of my cat eating a nano-banana in a" +
            "fancy restaurant under the Gemini constellation" },
    {
      inlineData: {
        mimeType: "image/png",
        data: base64Image,
      },
    },
  ];

  const response = await ai.models.generateContent({
    model: "gemini-2.5-flash-image-preview",
    contents: prompt,
  });
  for (const part of response.candidates[0].content.parts) {
    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/cat_image.png"
 imgData, _ := os.ReadFile(imagePath)

 parts := []*genai.Part{
   genai.NewPartFromText("Create a picture of my cat eating a nano-banana in a fancy restaurant under the Gemini constellation"),
   &genai.Part{
     InlineData: &genai.Blob{
       MIMEType: "image/png",
       Data:     imgData,
     },
   },
 }

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

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

 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/cat_image.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.5-flash-image-preview:generateContent" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d "{
      \"contents\": [{
        \"parts\":[
            {\"text\": \"'Create a picture of my cat eating a nano-banana in a fancy restaurant under the Gemini constellation\"},
            {
              \"inline_data\": {
                \"mime_type\":\"image/jpeg\",
                \"data\": \"$IMG_BASE64\"
              }
            }
        ]
      }]
    }"  \
  | grep -o '"data": "[^"]*"' \
  | cut -d'"' -f4 \
  | base64 --decode > gemini-edited-image.png
Hình ảnh do AI tạo về một chú mèo đang ăn chuối anano
Hình ảnh do AI tạo về một chú mèo đang ăn một quả chuối nano

Các chế độ tạo hình ảnh khác

Gemini hỗ trợ các chế độ tương tác khác với hình ảnh dựa trên cấu trúc câu lệnh và ngữ cảnh, bao gồm:

  • Văn bản thành hình ảnh và văn bản (xen kẽ): Tạo ra hình ảnh kèm theo văn bản liên quan.
    • Ví dụ về câu lệnh: "Tạo một công thức minh hoạ cho món paella."
  • Hình ảnh và văn bản sang hình ảnh và văn bản (xen kẽ): Sử dụng hình ảnh và văn bản đầu vào để tạo hình ảnh và văn bản mới có liên quan.
    • Ví dụ về câu lệnh: (Với hình ảnh một căn phòng có đồ nội thất) "Những màu sắc nào khác của ghế sofa sẽ phù hợp với không gian của tôi? Bạn có thể cập nhật hình ảnh không?"
  • Chỉnh sửa hình ảnh nhiều lượt (trò chuyện): Tiếp tục tạo và chỉnh sửa hình ảnh theo cách trò chuyện.
    • Câu lệnh mẫu: [tải ảnh một chiếc ô tô màu xanh dương lên.] , "Biến chiếc xe này thành xe mui trần", "Bây giờ, hãy thay đổi màu thành vàng."

Hướng dẫn và chiến lược đặt câu lệnh

Để nắm vững cách tạo hình ảnh bằng Gemini 2.5 Flash, bạn cần bắt đầu bằng một nguyên tắc cơ bản:

Mô tả cảnh, đừng chỉ liệt kê từ khoá. Điểm mạnh cốt lõi của mô hình này là khả năng hiểu ngôn ngữ một cách sâu sắc. Một đoạn văn kể chuyện, mô tả sẽ hầu như luôn tạo ra một hình ảnh tốt hơn, mạch lạc hơn so với một danh sách các từ rời rạc.

Câu lệnh để tạo hình ảnh

Các chiến lược sau đây sẽ giúp bạn tạo câu lệnh hiệu quả để tạo ra chính xác những hình ảnh mà bạn đang tìm kiếm.

1. Cảnh giống thật

Để có hình ảnh chân thực, hãy sử dụng các thuật ngữ nhiếp ảnh. Đề cập đến góc máy, loại ống kính, ánh sáng và các chi tiết nhỏ để hướng dẫn mô hình tạo ra kết quả chân thực như ảnh chụp.

Mẫu

A photorealistic [shot type] of [subject], [action or expression], set in
[environment]. The scene is illuminated by [lighting description], creating
a [mood] atmosphere. Captured with a [camera/lens details], emphasizing
[key textures and details]. The image should be in a [aspect ratio] format.

Câu lệnh

A photorealistic close-up portrait of an elderly Japanese ceramicist with
deep, sun-etched wrinkles and a warm, knowing smile. He is carefully
inspecting a freshly glazed tea bowl. The setting is his rustic,
sun-drenched workshop. The scene is illuminated by soft, golden hour light
streaming through a window, highlighting the fine texture of the clay.
Captured with an 85mm portrait lens, resulting in a soft, blurred background
(bokeh). The overall mood is serene and masterful. Vertical portrait
orientation.

Python

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

client = genai.Client()

# Generate an image from a text prompt
response = client.models.generate_content(
    model="gemini-2.5-flash-image-preview",
    contents="A photorealistic close-up portrait of an elderly Japanese ceramicist with deep, sun-etched wrinkles and a warm, knowing smile. He is carefully inspecting a freshly glazed tea bowl. The setting is his rustic, sun-drenched workshop with pottery wheels and shelves of clay pots in the background. The scene is illuminated by soft, golden hour light streaming through a window, highlighting the fine texture of the clay and the fabric of his apron. Captured with an 85mm portrait lens, resulting in a soft, blurred background (bokeh). The overall mood is serene and masterful.",
)

image_parts = [
    part.inline_data.data
    for part in response.candidates[0].content.parts
    if part.inline_data
]

if image_parts:
    image = Image.open(BytesIO(image_parts[0]))
    image.save('photorealistic_example.png')
    image.show()
Bức chân dung cận cảnh chân thực về một nghệ nhân gốm sứ Nhật Bản lớn tuổi...
Ảnh chân dung cận cảnh siêu thực của một nghệ nhân gốm Nhật Bản lớn tuổi...

2. Hình minh hoạ và hình dán cách điệu

Để tạo hình dán, biểu tượng hoặc thành phần, hãy nêu rõ kiểu và yêu cầu nền trong suốt.

Mẫu

A [style] sticker of a [subject], featuring [key characteristics] and a
[color palette]. The design should have [line style] and [shading style].
The background must be transparent.

Câu lệnh

A kawaii-style sticker of a happy red panda wearing a tiny bamboo hat. It's
munching on a green bamboo leaf. The design features bold, clean outlines,
simple cel-shading, and a vibrant color palette. The background must be white.

Python

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

client = genai.Client()

# Generate an image from a text prompt
response = client.models.generate_content(
    model="gemini-2.5-flash-image-preview",
    contents="A kawaii-style sticker of a happy red panda wearing a tiny bamboo hat. It's munching on a green bamboo leaf. The design features bold, clean outlines, simple cel-shading, and a vibrant color palette. The background must be white.",
)

image_parts = [
    part.inline_data.data
    for part in response.candidates[0].content.parts
    if part.inline_data
]

if image_parts:
    image = Image.open(BytesIO(image_parts[0]))
    image.save('red_panda_sticker.png')
    image.show()
Hình dán theo phong cách kawaii về một chú...
Hình dán theo phong cách kawaii về một chú gấu trúc đỏ đang vui vẻ...

3. Văn bản chính xác trong hình ảnh

Gemini có khả năng hiển thị văn bản vượt trội. Hãy mô tả rõ ràng về văn bản, kiểu chữ và thiết kế tổng thể.

Mẫu

Create a [image type] for [brand/concept] with the text "[text to render]"
in a [font style]. The design should be [style description], with a
[color scheme].

Câu lệnh

Create a modern, minimalist logo for a coffee shop called 'The Daily Grind'.
The text should be in a clean, bold, sans-serif font. The design should
feature a simple, stylized icon of a a coffee bean seamlessly integrated
with the text. The color scheme is black and white.

Python

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

client = genai.Client()

# Generate an image from a text prompt
response = client.models.generate_content(
    model="gemini-2.5-flash-image-preview",
    contents="Create a modern, minimalist logo for a coffee shop called 'The Daily Grind'. The text should be in a clean, bold, sans-serif font. The design should feature a simple, stylized icon of a a coffee bean seamlessly integrated with the text. The color scheme is black and white.",
)

image_parts = [
    part.inline_data.data
    for part in response.candidates[0].content.parts
    if part.inline_data
]

if image_parts:
    image = Image.open(BytesIO(image_parts[0]))
    image.save('logo_example.png')
    image.show()
Tạo một logo tối giản, hiện đại cho quán cà phê có tên là "The Daily Grind"...
Tạo một biểu trưng tối giản, hiện đại cho một quán cà phê có tên là "The Daily Grind"...

4. Bản mô phỏng sản phẩm và ảnh thương mại

Phù hợp để tạo ra những bức ảnh sản phẩm chuyên nghiệp, gọn gàng cho thương mại điện tử, quảng cáo hoặc hoạt động xây dựng thương hiệu.

Mẫu

A high-resolution, studio-lit product photograph of a [product description]
on a [background surface/description]. The lighting is a [lighting setup,
e.g., three-point softbox setup] to [lighting purpose]. The camera angle is
a [angle type] to showcase [specific feature]. Ultra-realistic, with sharp
focus on [key detail]. [Aspect ratio].

Câu lệnh

A high-resolution, studio-lit product photograph of a minimalist ceramic
coffee mug in matte black, presented on a polished concrete surface. The
lighting is a three-point softbox setup designed to create soft, diffused
highlights and eliminate harsh shadows. The camera angle is a slightly
elevated 45-degree shot to showcase its clean lines. Ultra-realistic, with
sharp focus on the steam rising from the coffee. Square image.

Python

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

client = genai.Client()

# Generate an image from a text prompt
response = client.models.generate_content(
    model="gemini-2.5-flash-image-preview",
    contents="A high-resolution, studio-lit product photograph of a minimalist ceramic coffee mug in matte black, presented on a polished concrete surface. The lighting is a three-point softbox setup designed to create soft, diffused highlights and eliminate harsh shadows. The camera angle is a slightly elevated 45-degree shot to showcase its clean lines. Ultra-realistic, with sharp focus on the steam rising from the coffee. Square image.",
)

image_parts = [
    part.inline_data.data
    for part in response.candidates[0].content.parts
    if part.inline_data
]

if image_parts:
    image = Image.open(BytesIO(image_parts[0]))
    image.save('product_mockup.png')
    image.show()
Ảnh chụp sản phẩm có độ phân giải cao, được chiếu sáng trong phòng chụp ảnh về một cốc cà phê tối giản bằng gốm...
Ảnh sản phẩm có độ phân giải cao, được chụp trong phòng chụp ảnh, cho thấy một chiếc cốc cà phê gốm tối giản...

5. Thiết kế tối giản và không gian âm

Rất phù hợp để tạo nền cho trang web, bản trình bày hoặc tài liệu tiếp thị nơi văn bản sẽ được đặt lên trên.

Mẫu

A minimalist composition featuring a single [subject] positioned in the
[bottom-right/top-left/etc.] of the frame. The background is a vast, empty
[color] canvas, creating significant negative space. Soft, subtle lighting.
[Aspect ratio].

Câu lệnh

A minimalist composition featuring a single, delicate red maple leaf
positioned in the bottom-right of the frame. The background is a vast, empty
off-white canvas, creating significant negative space for text. Soft,
diffused lighting from the top left. Square image.

Python

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

client = genai.Client()

# Generate an image from a text prompt
response = client.models.generate_content(
    model="gemini-2.5-flash-image-preview",
    contents="A minimalist composition featuring a single, delicate red maple leaf positioned in the bottom-right of the frame. The background is a vast, empty off-white canvas, creating significant negative space for text. Soft, diffused lighting from the top left. Square image.",
)

image_parts = [
    part.inline_data.data
    for part in response.candidates[0].content.parts
    if part.inline_data
]

if image_parts:
    image = Image.open(BytesIO(image_parts[0]))
    image.save('minimalist_design.png')
    image.show()
Một bố cục tối giản với một chiếc lá phong đỏ duy nhất, tinh tế...
Một bố cục tối giản với một chiếc lá phong đỏ duy nhất, tinh tế...

6. Nghệ thuật tuần tự (Bảng phân cảnh / Khung hình truyện tranh)

Dựa trên tính nhất quán của nhân vật và nội dung mô tả cảnh để tạo các bảng cho nghệ thuật kể chuyện bằng hình ảnh.

Mẫu

A single comic book panel in a [art style] style. In the foreground,
[character description and action]. In the background, [setting details].
The panel has a [dialogue/caption box] with the text "[Text]". The lighting
creates a [mood] mood. [Aspect ratio].

Câu lệnh

A single comic book panel in a gritty, noir art style with high-contrast
black and white inks. In the foreground, a detective in a trench coat stands
under a flickering streetlamp, rain soaking his shoulders. In the
background, the neon sign of a desolate bar reflects in a puddle. A caption
box at the top reads "The city was a tough place to keep secrets." The
lighting is harsh, creating a dramatic, somber mood. Landscape.

Python

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

client = genai.Client()

# Generate an image from a text prompt
response = client.models.generate_content(
    model="gemini-2.5-flash-image-preview",
    contents="A single comic book panel in a gritty, noir art style with high-contrast black and white inks. In the foreground, a detective in a trench coat stands under a flickering streetlamp, rain soaking his shoulders. In the background, the neon sign of a desolate bar reflects in a puddle. A caption box at the top reads \"The city was a tough place to keep secrets.\" The lighting is harsh, creating a dramatic, somber mood. Landscape.",
)

image_parts = [
    part.inline_data.data
    for part in response.candidates[0].content.parts
    if part.inline_data
]

if image_parts:
    image = Image.open(BytesIO(image_parts[0]))
    image.save('comic_panel.png')
    image.show()
Một khung truyện tranh theo phong cách nghệ thuật noir táo bạo...
Một khung hình truyện tranh duy nhất theo phong cách nghệ thuật noir thô ráp...

Câu lệnh chỉnh sửa hình ảnh

Những ví dụ này cho thấy cách cung cấp hình ảnh cùng với câu lệnh văn bản để chỉnh sửa, tạo thành phần và chuyển kiểu.

1. Thêm và xoá phần tử

Cung cấp hình ảnh và mô tả thay đổi của bạn. Mô hình sẽ khớp với phong cách, ánh sáng và góc nhìn của hình ảnh gốc.

Mẫu

Using the provided image of [subject], please [add/remove/modify] [element]
to/from the scene. Ensure the change is [description of how the change should
integrate].

Câu lệnh

"Using the provided image of my cat, please add a small, knitted wizard hat
on its head. Make it look like it's sitting comfortably and matches the soft
lighting of the photo."

Python

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

client = genai.Client()

# Base image prompt: "A photorealistic picture of a fluffy ginger cat sitting on a wooden floor, looking directly at the camera. Soft, natural light from a window."
image_input = Image.open('/path/to/your/cat_photo.png')
text_input = """Using the provided image of my cat, please add a small, knitted wizard hat on its head. Make it look like it's sitting comfortably and not falling off."""

# Generate an image from a text prompt
response = client.models.generate_content(
    model="gemini-2.5-flash-image-preview",
    contents=[text_input, image_input],
)

image_parts = [
    part.inline_data.data
    for part in response.candidates[0].content.parts
    if part.inline_data
]

if image_parts:
    image = Image.open(BytesIO(image_parts[0]))
    image.save('cat_with_hat.png')
    image.show()

Đầu vào

Đầu ra

Hình ảnh chân thực về một chú mèo lông xù màu gừng.
Một bức ảnh chân thực về một chú mèo lông xù màu gừng...
Dựa vào hình ảnh chú mèo của tôi, vui lòng thêm một chiếc mũ phù thuỷ nhỏ bằng len...
Dựa vào hình ảnh chú mèo của tôi, vui lòng thêm một chiếc mũ phù thuỷ nhỏ bằng len...

2. Chỉnh sửa cụ thể (Tạo mặt nạ ngữ nghĩa)

Xác định "mặt nạ" theo cách trò chuyện để chỉnh sửa một phần cụ thể của hình ảnh mà không ảnh hưởng đến các phần còn lại.

Mẫu

Using the provided image, change only the [specific element] to [new
element/description]. Keep everything else in the image exactly the same,
preserving the original style, lighting, and composition.

Câu lệnh

"Using the provided image of a living room, change only the blue sofa to be
a vintage, brown leather chesterfield sofa. Keep the rest of the room,
including the pillows on the sofa and the lighting, unchanged."

Python

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

client = genai.Client()

# Base image prompt: "A wide shot of a modern, well-lit living room with a prominent blue sofa in the center. A coffee table is in front of it and a large window is in the background."
living_room_image = Image.open('/path/to/your/living_room.png')
text_input = """Using the provided image of a living room, change only the blue sofa to be a vintage, brown leather chesterfield sofa. Keep the rest of the room, including the pillows on the sofa and the lighting, unchanged."""

# Generate an image from a text prompt
response = client.models.generate_content(
    model="gemini-2.5-flash-image-preview",
    contents=[living_room_image, text_input],
)

image_parts = [
    part.inline_data.data
    for part in response.candidates[0].content.parts
    if part.inline_data
]

if image_parts:
    image = Image.open(BytesIO(image_parts[0]))
    image.save('living_room_edited.png')
    image.show()

Đầu vào

Đầu ra

Một cảnh quay rộng về một phòng khách hiện đại, đủ ánh sáng...
Cảnh quay rộng về một phòng khách hiện đại, đủ ánh sáng...
Dựa vào hình ảnh phòng khách được cung cấp, hãy chỉ thay đổi chiếc ghế sofa màu xanh dương thành chiếc ghế sofa Chesterfield bằng da màu nâu theo phong cách cổ điển...
Dựa vào hình ảnh phòng khách được cung cấp, hãy chỉ thay đổi chiếc ghế sofa màu xanh dương thành chiếc ghế sofa bọc da màu nâu kiểu Chesterfield cổ điển...

3. Chuyển đổi kiểu

Cung cấp một hình ảnh và yêu cầu mô hình tạo lại nội dung của hình ảnh đó theo một phong cách nghệ thuật khác.

Mẫu

Transform the provided photograph of [subject] into the artistic style of [artist/art style]. Preserve the original composition but render it with [description of stylistic elements].

Câu lệnh

"Transform the provided photograph of a modern city street at night into the artistic style of Vincent van Gogh's 'Starry Night'. Preserve the original composition of buildings and cars, but render all elements with swirling, impasto brushstrokes and a dramatic palette of deep blues and bright yellows."

Python

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

client = genai.Client()

# Base image prompt: "A photorealistic, high-resolution photograph of a busy city street in New York at night, with bright neon signs, yellow taxis, and tall skyscrapers."
city_image = Image.open('/path/to/your/city.png')
text_input = """Transform the provided photograph of a modern city street at night into the artistic style of Vincent van Gogh's 'Starry Night'. Preserve the original composition of buildings and cars, but render all elements with swirling, impasto brushstrokes and a dramatic palette of deep blues and bright yellows."""

# Generate an image from a text prompt
response = client.models.generate_content(
    model="gemini-2.5-flash-image-preview",
    contents=[city_image, text_input],
)

image_parts = [
    part.inline_data.data
    for part in response.candidates[0].content.parts
    if part.inline_data
]

if image_parts:
    image = Image.open(BytesIO(image_parts[0]))
    image.save('city_style_transfer.png')
    image.show()

Đầu vào

Đầu ra

Một bức ảnh chân thực, có độ phân giải cao về một con phố nhộn nhịp trong thành phố...
Một bức ảnh chân thực, có độ phân giải cao về một con phố nhộn nhịp trong thành phố...
Biến đổi bức ảnh được cung cấp về một đường phố hiện đại vào ban đêm...
Biến đổi bức ảnh được cung cấp về một đường phố hiện đại trong thành phố vào ban đêm...

4. Bố cục nâng cao: Kết hợp nhiều hình ảnh

Cung cấp nhiều hình ảnh làm bối cảnh để tạo một cảnh ghép mới. Đây là lựa chọn hoàn hảo cho bản mô phỏng sản phẩm hoặc ảnh ghép sáng tạo.

Mẫu

Create a new image by combining the elements from the provided images. Take
the [element from image 1] and place it with/on the [element from image 2].
The final image should be a [description of the final scene].

Câu lệnh

"Create a professional e-commerce fashion photo. Take the blue floral dress
from the first image and let the woman from the second image wear it.
Generate a realistic, full-body shot of the woman wearing the dress, with
the lighting and shadows adjusted to match the outdoor environment."

Python

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

client = genai.Client()

# Base image prompts:
# 1. Dress: "A professionally shot photo of a blue floral summer dress on a plain white background, ghost mannequin style."
# 2. Model: "Full-body shot of a woman with her hair in a bun, smiling, standing against a neutral grey studio background."
dress_image = Image.open('/path/to/your/dress.png')
model_image = Image.open('/path/to/your/model.png')

text_input = """Create a professional e-commerce fashion photo. Take the blue floral dress from the first image and let the woman from the second image wear it. Generate a realistic, full-body shot of the woman wearing the dress, with the lighting and shadows adjusted to match the outdoor environment."""

# Generate an image from a text prompt
response = client.models.generate_content(
    model="gemini-2.5-flash-image-preview",
    contents=[dress_image, model_image, text_input],
)

image_parts = [
    part.inline_data.data
    for part in response.candidates[0].content.parts
    if part.inline_data
]

if image_parts:
    image = Image.open(BytesIO(image_parts[0]))
    image.save('fashion_ecommerce_shot.png')
    image.show()

Đầu vào 1

Đầu vào 2

Đầu ra

Một bức ảnh chuyên nghiệp chụp chiếc váy mùa hè có hoạ tiết hoa màu xanh dương...
Ảnh chụp chuyên nghiệp về một chiếc váy mùa hè màu xanh dương có hoạ tiết hoa...
Ảnh toàn thân của một người phụ nữ tóc búi...
Cảnh quay toàn thân của một người phụ nữ búi tóc...
Tạo ảnh chuyên nghiệp về thời trang cho trang thương mại điện tử...
Tạo ảnh thời trang chuyên nghiệp cho thương mại điện tử...

5. Giữ lại chi tiết có độ trung thực cao

Để đảm bảo các chi tiết quan trọng (chẳng hạn như khuôn mặt hoặc biểu trưng) được giữ nguyên trong quá trình chỉnh sửa, hãy mô tả các chi tiết đó một cách cụ thể cùng với yêu cầu chỉnh sửa của bạn.

Mẫu

Using the provided images, place [element from image 2] onto [element from
image 1]. Ensure that the features of [element from image 1] remain
completely unchanged. The added element should [description of how the
element should integrate].

Câu lệnh

"Take the first image of the woman with brown hair, blue eyes, and a neutral
expression. Add the logo from the second image onto her black t-shirt.
Ensure the woman's face and features remain completely unchanged. The logo
should look like it's naturally printed on the fabric, following the folds
of the shirt."

Python

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

client = genai.Client()

# Base image prompts:
# 1. Woman: "A professional headshot of a woman with brown hair and blue eyes, wearing a plain black t-shirt, against a neutral studio background."
# 2. Logo: "A simple, modern logo with the letters 'G' and 'A' in a white circle."
woman_image = Image.open('/path/to/your/woman.png')
logo_image = Image.open('/path/to/your/logo.png')
text_input = """Take the first image of the woman with brown hair, blue eyes, and a neutral expression. Add the logo from the second image onto her black t-shirt. Ensure the woman's face and features remain completely unchanged. The logo should look like it's naturally printed on the fabric, following the folds of the shirt."""

# Generate an image from a text prompt
response = client.models.generate_content(
    model="gemini-2.5-flash-image-preview",
    contents=[woman_image, logo_image, text_input],
)

image_parts = [
    part.inline_data.data
    for part in response.candidates[0].content.parts
    if part.inline_data
]

if image_parts:
    image = Image.open(BytesIO(image_parts[0]))
    image.save('woman_with_logo.png')
    image.show()

Đầu vào 1

Đầu vào 2

Đầu ra

Ảnh chân dung chuyên nghiệp của một người phụ nữ tóc nâu và mắt xanh...
Ảnh chân dung chuyên nghiệp của một phụ nữ có mái tóc nâu và đôi mắt xanh dương...
Một biểu trưng đơn giản, hiện đại với các chữ cái "G" và "A"...
Một biểu trưng đơn giản, hiện đại có các chữ cái "G" và "A"...
Chụp ảnh đầu tiên về người phụ nữ có mái tóc nâu, mắt xanh và vẻ mặt bình thường...
Chụp ảnh đầu tiên về người phụ nữ có mái tóc nâu, mắt xanh và biểu cảm trung tính...

Các phương pháp hay nhất

Để nâng kết quả từ tốt lên xuất sắc, hãy kết hợp những chiến lược chuyên nghiệp này vào quy trình làm việc của bạn.

  • Càng cụ thể càng tốt: Bạn càng cung cấp nhiều thông tin chi tiết, bạn càng có nhiều quyền kiểm soát. Thay vì "áo giáp giả tưởng", hãy mô tả: "áo giáp dạng tấm của người lùn được chạm khắc hoa văn lá bạc, có cổ áo cao và cầu vai có hình dáng như cánh chim ưng".
  • Cung cấp bối cảnh và ý định: Giải thích mục đích của hình ảnh. Khả năng hiểu ngữ cảnh của mô hình sẽ ảnh hưởng đến kết quả đầu ra cuối cùng. Ví dụ: "Tạo một biểu trưng cho một thương hiệu chăm sóc da tối giản, cao cấp" sẽ mang lại kết quả tốt hơn so với chỉ "Tạo một biểu trưng".
  • Lặp lại và tinh chỉnh: Đừng mong đợi một hình ảnh hoàn hảo ngay từ lần thử đầu tiên. Sử dụng tính chất đàm thoại của mô hình để thực hiện các thay đổi nhỏ. Tiếp tục đưa ra các câu lệnh như "Tuyệt vời, nhưng bạn có thể điều chỉnh ánh sáng ấm hơn một chút không?" hoặc "Giữ nguyên mọi thứ, nhưng thay đổi biểu cảm của nhân vật sao cho nghiêm túc hơn."
  • Sử dụng hướng dẫn từng bước: Đối với những cảnh phức tạp có nhiều phần tử, hãy chia câu lệnh thành các bước. "Trước tiên, hãy tạo một hình nền là khu rừng yên bình, mờ sương vào lúc bình minh. Sau đó, ở tiền cảnh, hãy thêm một bàn thờ bằng đá cổ được phủ rêu. Cuối cùng, hãy đặt một thanh kiếm phát sáng duy nhất lên trên bàn thờ."
  • Sử dụng "Câu lệnh phủ định ngữ nghĩa": Thay vì nói "không có ô tô", hãy mô tả cảnh mong muốn một cách tích cực: "một con đường vắng vẻ, không có dấu hiệu giao thông".
  • Kiểm soát Camera: Sử dụng ngôn ngữ nhiếp ảnh và điện ảnh để kiểm soát bố cục. Các thuật ngữ như wide-angle shot, macro shot, low-angle perspective.

Các điểm hạn chế

  • Để có hiệu suất tốt nhất, hãy sử dụng các ngôn ngữ sau: tiếng Anh, tiếng Tây Ban Nha (Mexico), tiếng Nhật, tiếng Trung (giản thể), tiếng Hindi (Ấn Độ).
  • Tính năng tạo hình ảnh không hỗ trợ dữ liệu đầu vào là âm thanh hoặc video.
  • Không phải lúc nào mô hình cũng tạo ra chính xác số lượng hình ảnh mà người dùng yêu cầu một cách rõ ràng.
  • Mô hình này hoạt động hiệu quả nhất khi có tối đa 3 hình ảnh làm dữ liệu đầu vào.
  • Khi tạo văn bản cho một hình ảnh, Gemini hoạt động hiệu quả nhất nếu bạn tạo văn bản trước rồi yêu cầu tạo hình ảnh có văn bản đó.
  • Chúng tôi hiện không hỗ trợ việc tải hình ảnh trẻ em lên ở Khu vực kinh tế Châu Âu (EEA), Thuỵ Sĩ và Vương quốc Anh.
  • Tất cả hình ảnh được tạo đều có hình mờ SynthID.

Trường hợp sử dụng Imagen

Ngoài việc sử dụng các tính năng tạo hình ảnh tích hợp của Gemini, bạn cũng có thể truy cập vào Imagen, mô hình tạo hình ảnh chuyên biệt của chúng tôi, thông qua Gemini API.

Thuộc tính Imagen Hình ảnh gốc của Gemini
Điểm mạnh Mô hình tạo hình ảnh mạnh mẽ nhất từ trước đến nay. Được đề xuất cho hình ảnh siêu thực, độ rõ nét cao hơn, chính tả và kiểu chữ được cải thiện. Đề xuất mặc định.
Tính linh hoạt vô song, khả năng hiểu ngữ cảnh và thao tác chỉnh sửa đơn giản, không cần mặt nạ. Có khả năng chỉnh sửa trong cuộc trò chuyện nhiều lượt một cách độc đáo.
Phạm vi cung cấp Phát hành rộng rãi Xem trước (Được phép sử dụng trong sản xuất)
Độ trễ Thấp. Được tối ưu hoá để đạt hiệu suất gần như theo thời gian thực. Cao hơn. Cần nhiều hoạt động tính toán hơn cho các chức năng nâng cao của tính năng này.
Chi phí Tiết kiệm chi phí cho các công việc chuyên biệt. 0,02 USD/hình ảnh đến 0,12 USD/hình ảnh Giá dựa trên mã thông báo. 30 USD cho mỗi 1 triệu mã thông báo đối với đầu ra là hình ảnh (đầu ra là hình ảnh được mã hoá thành mã thông báo ở mức cố định là 1.290 mã thông báo cho mỗi hình ảnh, tối đa 1024x1024px)
Việc cần làm được đề xuất
  • Chất lượng hình ảnh, độ chân thực, chi tiết nghệ thuật hoặc phong cách cụ thể (ví dụ: trường phái ấn tượng, hoạt hình Nhật Bản) là những yếu tố được ưu tiên hàng đầu.
  • Truyền tải thương hiệu, phong cách hoặc tạo biểu trưng và thiết kế sản phẩm.
  • Tạo lỗi chính tả hoặc lỗi kiểu chữ nâng cao.
  • Tạo văn bản và hình ảnh xen kẽ để kết hợp liền mạch văn bản và hình ảnh.
  • Kết hợp các thành phần mẫu quảng cáo từ nhiều hình ảnh chỉ bằng một câu lệnh.
  • Chỉnh sửa hình ảnh theo cách cụ thể, sửa đổi từng phần tử bằng các câu lệnh đơn giản và chỉnh sửa lặp đi lặp lại một hình ảnh.
  • Áp dụng một thiết kế hoặc hoạ tiết cụ thể từ hình ảnh này sang hình ảnh khác mà vẫn giữ nguyên hình dạng và chi tiết của đối tượng ban đầu.

Imagen 4 là mô hình bạn nên dùng để bắt đầu tạo hình ảnh bằng Imagen. Chọn Imagen 4 Ultra cho các trường hợp sử dụng nâng cao hoặc khi bạn cần chất lượng hình ảnh tốt nhất (lưu ý rằng bạn chỉ có thể tạo một hình ảnh tại một thời điểm).

Bước tiếp theo