Gemini может генерировать и обрабатывать изображения в режиме диалога. Вы можете задавать Gemini текст, изображения или их комбинацию, что позволяет создавать, редактировать и дорабатывать визуальные материалы с беспрецедентным контролем:
- Преобразование текста в изображение: создание высококачественных изображений из простых или сложных текстовых описаний.
- Изображение + Текст в изображение (редактирование): укажите изображение и используйте текстовые подсказки для добавления, удаления или изменения элементов, изменения стиля или настройки цветовой градации.
- Перенос нескольких изображений на одно изображение (композиция и стиль): используйте несколько входных изображений для компоновки новой сцены или переноса стиля с одного изображения на другое.
- Последовательное совершенствование: участвуйте в обсуждении, чтобы постепенно совершенствовать свое изображение в течение нескольких этапов, внося небольшие изменения, пока оно не станет идеальным.
- Высокоточная визуализация текста: точное создание изображений, содержащих разборчивый и удачно расположенный текст, идеально подходящий для логотипов, диаграмм и плакатов.
Все сгенерированные изображения содержат водяной знак SynthID .
Генерация изображений (текст в изображение)
Следующий код демонстрирует, как создать изображение на основе описательной подсказки.
Питон
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();
Идти
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)
}
}
}
ОТДЫХ
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

Редактирование изображений (текст и изображение в изображение)
Напоминание : убедитесь, что у вас есть необходимые права на любые загружаемые изображения. Не создавайте контент, нарушающий права других лиц, включая видео или изображения, которые вводят в заблуждение, преследуют или причиняют вред. Использование вами этого сервиса искусственного интеллекта регулируется нашей Политикой запрещённого использования .
Чтобы отредактировать изображение, добавьте его в качестве входных данных. В следующем примере показана загрузка изображений в кодировке Base64. Информация о нескольких изображениях, объёме полезной нагрузки и поддерживаемых типах MIME представлена на странице «Понимание изображений» .
Питон
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();
Идти
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)
}
}
}
ОТДЫХ
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

Другие режимы генерации изображений
Gemini поддерживает другие режимы взаимодействия с изображениями на основе структуры подсказки и контекста, включая:
- Текст с изображением(ями) и текстом (чередование): выводит изображения с соответствующим текстом.
- Пример задания: «Создайте иллюстрированный рецепт паэльи».
- Изображение(я) и текст в изображение(я) и текст (чередование) : использует входные изображения и текст для создания новых связанных изображений и текста.
- Пример вопроса: (На изображении меблированной комнаты) «Какие еще цвета диванов подойдут для моего помещения? Можете ли вы обновить изображение?»
- Многоэтапное редактирование изображений (чат): продолжайте создавать и редактировать изображения в режиме диалога.
- Примеры подсказок: [загрузите изображение синего автомобиля.] , «Преврати эту машину в кабриолет.», «Теперь измени цвет на желтый».
Руководство и стратегии
Освоение генерации Flash-изображений Gemini 2.5 начинается с одного основополагающего принципа:
Описывайте сцену, а не просто перечисляйте ключевые слова. Главное преимущество модели — глубокое понимание языка. Повествовательный, описательный абзац почти всегда создаст более связное и связное изображение, чем список разрозненных слов.
Подсказки для генерации изображений
Следующие стратегии помогут вам создать эффективные подсказки для генерации именно тех изображений, которые вы ищете.
1. Фотореалистичные сцены
Для реалистичных изображений используйте термины из области фотографии. Укажите ракурсы, типы объективов, освещение и мелкие детали, чтобы помочь модели достичь фотореалистичного результата.
Шаблон
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.
Быстрый
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.
Питон
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()

2. Стилизованные иллюстрации и наклейки
Чтобы создать наклейки, значки или ресурсы, четко укажите стиль и запросите прозрачный фон.
Шаблон
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.
Быстрый
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.
Питон
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()

3. Точный текст на изображениях
Gemini превосходно передает текст. Четко формулируйте текст, стиль шрифта (описательно) и общий дизайн.
Шаблон
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].
Быстрый
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.
Питон
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()

4. Макеты продукции и коммерческая фотосъемка
Идеально подходит для создания четких, профессиональных снимков продукции для электронной коммерции, рекламы или брендинга.
Шаблон
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].
Быстрый
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.
Питон
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()

5. Минималистичный дизайн с негативным пространством
Отлично подходит для создания фонов для веб-сайтов, презентаций или маркетинговых материалов, где будет наложен текст.
Шаблон
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].
Быстрый
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.
Питон
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()

6. Последовательное искусство (комикс / раскадровка)
Создает панели для визуального повествования на основе последовательности персонажей и описания сцен.
Шаблон
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].
Быстрый
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.
Питон
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()

Подсказки для редактирования изображений
В этих примерах показано, как предоставлять изображения вместе с текстовыми подсказками для редактирования, композиции и переноса стиля.
1. Добавление и удаление элементов
Предоставьте изображение и опишите изменения. Модель будет соответствовать стилю, освещению и перспективе исходного изображения.
Шаблон
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].
Быстрый
"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."
Питон
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()
Вход | Выход |
![]() | ![]() |
2. Инкартирование (семантическая маскировка)
В разговорной речи можно определить «маску», чтобы отредактировать определенную часть изображения, оставив остальную часть нетронутой.
Шаблон
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.
Быстрый
"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."
Питон
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()
Вход | Выход |
![]() | ![]() |
3. Перенос стиля
Предоставьте изображение и попросите модель воссоздать его содержание в другом художественном стиле.
Шаблон
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].
Быстрый
"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."
Питон
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()
Вход | Выход |
![]() | ![]() |
4. Продвинутая композиция: объединение нескольких изображений
Используйте несколько изображений в качестве контекста для создания новой, составной сцены. Это идеально подходит для макетов продуктов или креативных коллажей.
Шаблон
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].
Быстрый
"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."
Питон
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()
Вход 1 | Вход 2 | Выход |
![]() | ![]() | ![]() |
5. Высокоточное сохранение деталей
Чтобы гарантировать сохранение важных деталей (например, лица или логотипа) во время редактирования, опишите их как можно подробнее вместе с запросом на редактирование.
Шаблон
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].
Быстрый
"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."
Питон
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()
Вход 1 | Вход 2 | Выход |
![]() | ![]() | ![]() |
Лучшие практики
Чтобы поднять результаты с хороших до отличных, включите эти профессиональные стратегии в свой рабочий процесс.
- Будьте предельно конкретны: чем больше деталей вы предоставите, тем больше контроля у вас будет. Вместо «фэнтезийные доспехи» опишите их так: «изысканная эльфийская пластинчатая броня, украшенная узорами из серебряных листьев, с высоким воротником и наплечниками в форме соколиных крыльев».
- Укажите контекст и цель: объясните назначение изображения. Понимание контекста моделью повлияет на конечный результат. Например, запрос «Создать логотип для бренда элитных минималистичных средств по уходу за кожей» даст лучшие результаты, чем просто «Создать логотип».
- Повторяйте и дорабатывайте: не ждите идеального изображения с первой попытки. Используйте разговорную природу модели, чтобы внести небольшие изменения. Продолжайте подсказками, например: «Отлично, но можно ли сделать освещение чуть теплее?» или «Оставьте всё как есть, но измените выражение лица персонажа на более серьёзное».
- Используйте пошаговые инструкции: для сложных сцен со множеством элементов разбейте задание на этапы. «Сначала создайте фон в виде безмятежного туманного леса на рассвете. Затем на переднем плане добавьте покрытый мхом древний каменный алтарь. Наконец, поместите на алтарь один светящийся меч».
- Используйте «семантические отрицательные подсказки»: вместо того, чтобы сказать «машин нет», опишите желаемую сцену позитивно: «пустая, безлюдная улица без признаков движения».
- Управляйте камерой: используйте фотографический и кинематографический язык для управления композицией. Например,
wide-angle shot
,macro shot
,low-angle perspective
.
Ограничения
- Для наилучшей производительности используйте следующие языки: EN, es-MX, ja-JP, zh-CN, hi-IN.
- Генерация изображений не поддерживает аудио- и видеовходы.
- Модель не всегда будет выводить именно то количество изображений, которое явно запросил пользователь.
- Модель лучше всего работает, если в качестве входных данных используется до 3 изображений.
- При генерации текста для изображения Gemini работает лучше всего, если вы сначала генерируете текст, а затем запрашиваете изображение с текстом.
- Загрузка изображений детей в настоящее время не поддерживается в ЕЭЗ, Швейцарии и Великобритании.
- Все сгенерированные изображения содержат водяной знак SynthID .
Когда использовать Imagen
Помимо использования встроенных возможностей генерации изображений Gemini, вы также можете получить доступ к Imagen , нашей специализированной модели генерации изображений, через API Gemini.
Атрибут | Имиджен | Родной образ Близнецов |
---|---|---|
Сильные стороны | Самая мощная на сегодняшний день модель генерации изображений. Рекомендуется для создания фотореалистичных изображений, повышения чёткости, улучшения орфографии и типографики. | Рекомендация по умолчанию. Непревзойденная гибкость, понимание контекста и простое редактирование без масок. Уникальная возможность многопоточного диалогового редактирования. |
Доступность | Доступно всем | Предварительный просмотр (разрешено использование в производстве) |
Задержка | Низкий . Оптимизирован для работы в режиме, близком к реальному времени. | Выше. Для его расширенных возможностей требуется больше вычислений. |
Расходы | Экономически выгодно для специализированных задач. 0,02–0,12 долл. США за изображение. | Цена на основе токенов. 30 долларов США за 1 миллион токенов за вывод изображения (токенизация изображения производится по 1290 токенов на изображение размером до 1024x1024 пикселей). |
Рекомендуемые задачи |
|
|
Imagen 4 — ваш выбор, если вы начинаете создавать изображения с помощью Imagen. Выбирайте Imagen 4 Ultra для сложных задач или когда вам требуется наилучшее качество изображения (обратите внимание, что одновременно можно создавать только одно изображение).
Что дальше?
- Дополнительные примеры и образцы кода можно найти в кулинарном руководстве .
- Ознакомьтесь с руководством Veo , чтобы узнать, как создавать видео с помощью API Gemini.
- Более подробную информацию о моделях Gemini можно найти в разделе Модели Gemini .