สร้างรูปภาพ

Gemini API รองรับการสร้างรูปภาพโดยใช้ Gemini 2.0 Flash Experimental และโดยใช้ Imagen 3 คู่มือนี้จะช่วยคุณเริ่มต้นใช้งานทั้ง 2 รุ่น

สร้างรูปภาพโดยใช้ Gemini

Gemini 2.0 Flash Experimental รองรับการแสดงผลข้อความและรูปภาพในบรรทัด ซึ่งจะช่วยให้คุณใช้ Gemini เพื่อแก้ไขรูปภาพแบบการสนทนาหรือสร้างเอาต์พุตที่มีข้อความแทรกอยู่ (เช่น สร้างบล็อกโพสต์ที่มีข้อความและรูปภาพในรอบเดียว) รูปภาพที่สร้างขึ้นทั้งหมดจะมีลายน้ำ SynthID และรูปภาพใน Google AI Studio จะมีลายน้ำที่มองเห็นได้เช่นกัน

ตัวอย่างต่อไปนี้แสดงวิธีใช้ Gemini 2.0 เพื่อสร้างเอาต์พุตข้อความและรูปภาพ

PythonNode.jsREST
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-exp-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()
const { GoogleGenerativeAI } = require("@google/generative-ai");
const fs = require("fs");

const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);

async function generateImage() {
  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 model = genAI.getGenerativeModel({
    model: "gemini-2.0-flash-exp-image-generation",
    generationConfig: {
        responseModalities: ['Text', 'Image']
    },
  });

  try {
    const response = await model.generateContent(contents);
    for (const part of  response.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');
      }
    }
  } catch (error) {
    console.error("Error generating content:", error);
  }
}

generateImage();
curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp-image-generation:generateContent?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 สร้างขึ้น

Gemini จะสร้างเนื้อหาในโหมดต่างๆ (ข้อความเป็นรูปภาพ ข้อความเป็นทั้งรูปภาพและข้อความ ฯลฯ) ทั้งนี้ขึ้นอยู่กับพรอมต์และบริบท โดยมีตัวอย่างดังนี้

  • การเปลี่ยนข้อความเป็นรูปภาพ
    • ตัวอย่างพรอมต์: "สร้างรูปภาพหอไอเฟลที่มีพลุเป็นพื้นหลัง"
  • ข้อความเป็นรูปภาพและข้อความ (สลับกัน)
    • ตัวอย่างพรอมต์: "สร้างสูตรอาหารพร้อมภาพสำหรับข้าวผัดพริกปาเอลยา"
  • รูปภาพและข้อความเป็นรูปภาพและข้อความ (สลับกัน)
    • ตัวอย่างพรอมต์: (มีรูปภาพห้องที่มีเฟอร์นิเจอร์) "โซฟาสีอื่นใดที่เหมาะกับพื้นที่ของฉันบ้าง คุณอัปเดตรูปภาพได้ไหม"
  • การแก้ไขรูปภาพ (ข้อความและรูปภาพต่อรูปภาพ)
    • ตัวอย่างพรอมต์: "แก้ไขรูปภาพนี้ให้ดูเหมือนการ์ตูน"
    • ตัวอย่างพรอมต์: [รูปแมว] + [รูปหมอน] + "สร้างงานปักครอสติชรูปแมวของฉันบนหมอนนี้"
  • การแก้ไขรูปภาพแบบหลายรอบ (แชท)
    • ตัวอย่างพรอมต์: [อัปโหลดรูปภาพรถสีน้ำเงิน] "เปลี่ยนรถคันนี้เป็นรถเปิดประทุน" "ตอนนี้เปลี่ยนเป็นสีเหลือง"

การแก้ไขรูปภาพด้วย Gemini

หากต้องการทำการแก้ไขรูปภาพ ให้เพิ่มรูปภาพเป็นอินพุต ตัวอย่างต่อไปนี้แสดงการอัปโหลดรูปภาพที่เข้ารหัส Base64 สำหรับรูปภาพหลายรูปและเพย์โหลดขนาดใหญ่ ให้ดูที่ส่วนอินพุตรูปภาพ

PythonNode.jsREST
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-exp-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()
const { GoogleGenerativeAI } = require("@google/generative-ai");
const fs = require("fs");

const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);

async function generateImage() {
    // 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: "Hi, This is a picture of me. Can you add a llama next to me?" },
        {
          inlineData: {
            mimeType: 'image/png',
            data: base64Image
          }
        }
      ];

  // Set responseModalities to include "Image" so the model can generate an image
  const model = genAI.getGenerativeModel({
    model: "gemini-2.0-flash-exp-image-generation",
    generationConfig: {
        responseModalities: ['Text', 'Image']
    },
  });

  try {
    const response = await model.generateContent(contents);
    for (const part of  response.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');
      }
    }
  } catch (error) {
    console.error("Error generating content:", error);
  }
}

generateImage();
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-exp-image-generation:generateContent?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 จะทำงานได้ดีที่สุดหากคุณสร้างข้อความก่อนแล้วจึงขอรูปภาพที่มีข้อความ

เลือกรุ่น

คุณควรใช้โมเดลใดในการสร้างรูปภาพ ขึ้นอยู่กับกรณีการใช้งานของคุณ

Gemini 2.0 เหมาะอย่างยิ่งสำหรับการสร้างรูปภาพที่ตรงตามบริบท การผสมผสานข้อความและรูปภาพ การใช้ความรู้ทั่วไป และการหาเหตุผลเกี่ยวกับรูปภาพ คุณสามารถใช้ฟีเจอร์นี้เพื่อสร้างภาพที่มีความแม่นยำและมีความเกี่ยวข้องตามบริบทซึ่งฝังอยู่ในข้อความยาวๆ นอกจากนี้ คุณยังแก้ไขรูปภาพในลักษณะการสนทนาโดยใช้ภาษาที่เป็นธรรมชาติได้ พร้อมกับคงบริบทไว้ตลอดการสนทนา

หากคุณภาพของรูปภาพเป็นสิ่งสำคัญที่สุด Imagen 3 จะเป็นตัวเลือกที่ดีกว่า Imagen 3 โดดเด่นในเรื่องภาพเหมือนจริง รายละเอียดทางศิลปะ และสไตล์ศิลปะที่เฉพาะเจาะจง เช่น อิมเพรสชันนิสม์หรืออะนิเมะ Imagen 3 ยังเหมาะสําหรับงานแก้ไขรูปภาพเฉพาะทาง เช่น การอัปเดตพื้นหลังผลิตภัณฑ์ การเพิ่มขนาดรูปภาพ และการใช้การสร้างแบรนด์และสไตล์ในภาพ คุณสามารถใช้ Imagen 3 เพื่อสร้างโลโก้หรือการออกแบบผลิตภัณฑ์อื่นๆ ที่มีแบรนด์

สร้างรูปภาพโดยใช้ Imagen 3

Gemini API ให้สิทธิ์เข้าถึง Imagen 3 ซึ่งเป็นโมเดลการเปลี่ยนข้อความเป็นรูปภาพคุณภาพสูงสุดของ Google ที่มาพร้อมความสามารถใหม่ๆ และความสามารถที่ปรับปรุงแล้วมากมาย Imagen 3 สามารถทำสิ่งต่อไปนี้

  • สร้างรูปภาพที่มีรายละเอียดดีขึ้น แสงสว่างมากขึ้น และข้อบกพร่องที่รบกวนสายตาน้อยลงกว่ารุ่นก่อนหน้า
  • ทําความเข้าใจพรอมต์ที่เขียนด้วยภาษาที่เป็นธรรมชาติ
  • สร้างรูปภาพในหลากหลายรูปแบบและสไตล์
  • แสดงผลข้อความได้มีประสิทธิภาพมากกว่ารุ่นก่อนหน้า

ตัวอย่าง Imagen

ส่วนนี้จะแสดงวิธีสร้างอินสแตนซ์โมเดล Imagen และสร้างรูปภาพ

หลังจากติดตั้ง Google Gen AI SDK แล้ว คุณจะใช้โค้ดต่อไปนี้เพื่อสร้างรูปภาพได้

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

client = genai.Client(api_key='GEMINI_API_KEY')

response = client.models.generate_images(
    model='imagen-3.0-generate-002',
    prompt='Fuzzy bunnies in my kitchen',
    config=types.GenerateImagesConfig(
        number_of_images= 4,
    )
)
for generated_image in response.generated_images:
  image = Image.open(BytesIO(generated_image.image.image_bytes))
  image.show()
curl -X POST \
    "https://generativelanguage.googleapis.com/v1beta/models/imagen-3.0-generate-002:predict?key=GEMINI_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
        "instances": [
          {
            "prompt": "Fuzzy bunnies in my kitchen"
          }
        ],
        "parameters": {
          "sampleCount": 4
        }
      }'

ตัวอย่างโค้ดควรแสดงผลรูปภาพ 4 รูปที่คล้ายกับรูปภาพนี้

รูปภาพกระต่ายขนปุกปุย 2 ตัวในครัวที่ AI สร้างขึ้น

นอกจากนี้ คุณยังลองใช้คู่มือเริ่มต้นใช้งานโน้ตบุ๊ก Imagen ในตำราอาหารสำหรับ Gemini ได้ด้วย

พารามิเตอร์โมเดล Imagen

พารามิเตอร์ต่อไปนี้พร้อมใช้งานสําหรับ generate_images()

  • prompt: ข้อความพรอมต์สำหรับรูปภาพ
  • number_of_images: จำนวนรูปภาพที่จะสร้าง ตั้งแต่ 1 ถึง 4 (รวม) ค่าเริ่มต้นคือ 4
  • aspect_ratio: เปลี่ยนสัดส่วนภาพของรูปภาพที่สร้างขึ้น ค่าที่รองรับคือ "1:1", "3:4", "4:3", "9:16" และ "16:9" โดยมีค่าเริ่มต้นเป็น "1:1"
  • safety_filter_level: เพิ่มระดับตัวกรองให้กับการกรองเพื่อความปลอดภัย ค่าที่ใช้ได้มีดังนี้
    • "BLOCK_LOW_AND_ABOVE": บล็อกเมื่อคะแนนความน่าจะเป็นหรือคะแนนความรุนแรงเป็น LOW, MEDIUM หรือ HIGH
    • "BLOCK_MEDIUM_AND_ABOVE": บล็อกเมื่อคะแนนความน่าจะเป็นหรือคะแนนความรุนแรงเป็น MEDIUM หรือ HIGH
    • "BLOCK_ONLY_HIGH": บล็อกเมื่อคะแนนความน่าจะเป็นหรือคะแนนความรุนแรงเป็น HIGH
  • person_generation: อนุญาตให้โมเดลสร้างรูปภาพคน ค่าที่รองรับมีดังนี้
    • "DONT_ALLOW": บล็อกการสร้างรูปภาพคน
    • "ALLOW_ADULT": สร้างรูปภาพผู้ใหญ่ แต่ไม่สร้างรูปภาพเด็ก ซึ่งเป็นค่าเริ่มต้น

ระบบจะเพิ่มลายน้ำดิจิทัล SynthID ที่มองไม่เห็นลงในรูปภาพที่สร้างขึ้นเสมอ

ภาษาของข้อความพรอมต์

ระบบรองรับภาษาพรอมต์ข้อความอินพุตต่อไปนี้

  • อังกฤษ (en)

ขั้นตอนถัดไป