對接gemini-2.5-flash-image-preview教程

對接gemini-2.5-flash-image-preview教程

一、前置準備

1. 明確模型要求

本次對接的gemini-2.5-flash-image-preview模型,繼承Gemini系列多模態特性,支持文本生成圖片、文本結合圖片編輯等功能。需注意該模型不支持僅輸出圖片,必須配置["TEXT", "IMAGE"]雙模態輸出;所有生成圖片均含SynthID水印,當前支持英語、西班牙語(墨西哥)、日語、簡體中文、印地語等語言提示詞,暫不支持音頻或視頻輸入。

2. 環境配置

  • 安裝基礎網絡請求工具:如Python的requests庫、JavaScript的axios庫,用于向指定BaseURL發送API請求。
  • 準備Base64編碼工具:若涉及圖片編輯,需將本地圖片轉為Base64格式傳入請求參數。
  • 獲取Gemini API密鑰(GEMINI_API_KEY):用于身份驗證,需在請求頭或參數中攜帶(若BaseURL接口已集成密鑰管理,可省略此步驟)。

二、核心功能對接步驟

1. 文本生成圖片(Text-to-Image)

通過文本提示詞生成對應圖片,以下為不同編程語言實現示例,均基于指定BaseURL(http://api.aaigc.top)開發。

Python實現
import requests
import base64
from io import BytesIO
from PIL import Image# 配置基礎信息
BASE_URL = "http://api.aaigc.top"
ENDPOINT = "/v1beta/models/gemini-2.5-flash-image-preview:generateContent"  # 接口端點(參考Gemini API規范,以實際為準)
API_KEY = "你的GEMINI_API_KEY"  # 接口集成密鑰時可刪除# 文本提示詞
prompt = "3D渲染風格:戴禮帽、長翅膀的小豬,飛越滿是綠色植物的未來科幻城市,城市高樓林立且帶霓虹燈光"# 構造請求參數
payload = {"contents": [{"parts": [{"text": prompt}]}],"generationConfig": {"responseModalities": ["TEXT", "IMAGE"]}  # 必須雙模態輸出
}# 構造請求頭
headers = {"Content-Type": "application/json","Authorization": f"Bearer {API_KEY}"  # 接口集成密鑰時可刪除
}# 發送請求并處理響應
response = requests.post(f"{BASE_URL}{ENDPOINT}", json=payload, headers=headers)
response.raise_for_status()
data = response.json()# 解析文本與圖片
for part in data["candidates"][0]["content"]["parts"]:if "text" in part and part["text"]:print("模型文本回復:", part["text"])elif "inlineData" in part and part["inlineData"]["data"]:image_data = base64.b64decode(part["inlineData"]["data"])image = Image.open(BytesIO(image_data))image.save("gemini-text-to-image.png")image.show()print("圖片已保存:gemini-text-to-image.png")
JavaScript實現(Node.js環境)
const axios = require('axios');
const fs = require('fs');
const path = require('path');// 配置基礎信息
const BASE_URL = "http://api.aaigc.top";
const ENDPOINT = "/v1beta/models/gemini-2.5-flash-image-preview:generateContent";
const API_KEY = "你的GEMINI_API_KEY";// 文本提示詞
const prompt = "3D渲染風格:戴禮帽、長翅膀的小豬,飛越滿是綠色植物的未來科幻城市,城市高樓林立且帶霓虹燈光";// 構造請求參數
const payload = {"contents": [{"parts": [{"text": prompt}]}],"generationConfig": {"responseModalities": ["TEXT", "IMAGE"]}
};// 構造請求頭
const headers = {"Content-Type": "application/json","Authorization": `Bearer ${API_KEY}`
};// 發送請求并處理響應
async function generateImageFromText() {try {const response = await axios.post(`${BASE_URL}${ENDPOINT}`, payload, { headers });const data = response.data;for (const part of data.candidates[0].content.parts) {if (part.text) {console.log("模型文本回復:", part.text);} else if (part.inlineData && part.inlineData.data) {const imageBuffer = Buffer.from(part.inlineData.data, 'base64');const savePath = path.join(__dirname, "gemini-text-to-image.png");fs.writeFileSync(savePath, imageBuffer);console.log(`圖片已保存:${savePath}`);}}} catch (error) {console.error("請求失敗:", error.response?.data || error.message);}
}generateImageFromText();

2. 圖片編輯(Image + Text-to-Image)

傳入Base64格式原始圖片與編輯提示詞,模型將按要求修改圖片,關鍵步驟如下:

前置操作:圖片轉Base64(Python示例)
import base64def image_to_base64(image_path):with open(image_path, "rb") as image_file:return base64.b64encode(image_file.read()).decode("utf-8")# 轉換本地圖片
original_image_path = "original-image.png"
image_base64 = image_to_base64(original_image_path)
Python編輯圖片示例
import requests
import base64
from io import BytesIO
from PIL import Image# 配置基礎信息(同文本生成圖片)
BASE_URL = "http://api.aaigc.top"
ENDPOINT = "/v1beta/models/gemini-2.5-flash-image-preview:generateContent"
API_KEY = "你的GEMINI_API_KEY"# 原始圖片Base64編碼
original_image_path = "original-image.png"
image_base64 = image_to_base64(original_image_path)# 編輯提示詞
edit_prompt = "在人物身旁添加一只白色羊駝,羊駝面向人物,整體風格與原圖保持一致(如原圖寫實,羊駝也需寫實)"# 構造請求參數
payload = {"contents": [{"parts": [{"text": edit_prompt},{"inlineData": {"mimeType": "image/png", "data": image_base64}}  # 匹配圖片實際格式]}],"generationConfig": {"responseModalities": ["TEXT", "IMAGE"]}
}# 構造請求頭(同文本生成圖片)
headers = {"Content-Type": "application/json","Authorization": f"Bearer {API_KEY}"
}# 發送請求并解析響應
response = requests.post(f"{BASE_URL}{ENDPOINT}", json=payload, headers=headers)
response.raise_for_status()
data = response.json()# 保存編輯后圖片
for part in data["candidates"][0]["content"]["parts"]:if "inlineData" in part and part["inlineData"]["data"]:image_data = base64.b64decode(part["inlineData"]["data"])edited_image = Image.open(BytesIO(image_data))edited_image.save("gemini-edited-image.png")edited_image.show()print("編輯后圖片已保存:gemini-edited-image.png")elif "text" in part and part["text"]:print("模型編輯說明:", part["text"])

三、常見問題與注意事項

  1. 僅輸出文本:需在提示詞中明確包含“生成圖片”“更新圖片”等指令,如將“添加羊駝”改為“生成添加羊駝后的圖片”。
  2. 生成中斷:重試請求或簡化提示詞,避免單次提示包含過多元素。
  3. Base64編碼錯誤:確保編碼完整(無多余空格/換行),且mimeType與圖片格式一致(JPG對應image/jpeg,PNG對應image/png)。
  4. 地區可用性:若提示“服務暫不可用”,需確認當前地區是否開放該模型功能,可參考BaseURL接口的地區支持說明。

四、案例

1.以下為一張卡哇伊風格的快樂小熊貼紙。背景為設定的白色,整體采用清晰輪廓和大膽配色,整個設計十分生動和吸引人

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].1from google import genai2from google.genai import types3from PIL import Image4from io import BytesIO56client = genai.Client()78# Generate an image from a text prompt9response = client.models.generate_content(
10    model="gemini-2.5-flash-image-preview",
11    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.",
12)
13
14image_parts = [
15    part.inline_data.data
16    for part in response.candidates[0].content.parts
17    if part.inline_data
18]
19
20if image_parts:
21    image = Image.open(BytesIO(image_parts[0]))
22    image.save('logo_example.png')
23    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 white.1from google import genai2from google.genai import types3from PIL import Image4from io import BytesIO56client = genai.Client()78# Generate an image from a text prompt9response = client.models.generate_content(
10    model="gemini-2.5-flash-image-preview",
11    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.",
12)
13
14image_parts = [
15    part.inline_data.data
16    for part in response.candidates[0].content.parts
17    if part.inline_data
18]
19
20if image_parts:
21    image = Image.open(BytesIO(image_parts[0]))
22    image.save('photorealistic_example.png')
23    image.show()

3.貓貓在雙子座星空下的豪華餐廳里吃香蕉。哇哦,貓貓桌子上還擺著刀叉和酒杯,餐廳里其他桌子上也有客人,真是充滿了細節。

 1    from google import genai2    from google.genai import types3    from PIL import Image4    from io import BytesIO56    client = genai.Client()78    # Generate an image from a text prompt9    response = client.models.generate_content(
10    model="gemini-2.5-flash-image-preview",
11    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.",
12    )
13
14    image_parts = [
15    part.inline_data.data
16    for part in response.candidates[0].content.parts
17    if part.inline_data
18    ]
19
20    if image_parts:
21    image = Image.open(BytesIO(image_parts[0]))
22    image.save('photorealistic_example.png')

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/95712.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/95712.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/95712.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

如何制造一個AI Agent:從“人工智障”到“人工智能”的奇幻漂流

開篇:什么是AI Agent?它和我的“人工智障”音箱有啥區別?🎤朋友們,先想象一下:你的智能音箱 🗣? -> 🤖 -> ?:“Hey Siri,幫我訂一份披薩,…

別錯過!一杯奶茶錢開啟企業微信 Power BI 之旅

隨著微軟的Power BI在數據分析和商業智能領域的廣泛應用,人們對于Power BI使用的便捷性和高效性提出了更高的要求。 為了滿足這些需求,PBI Plus應運而生,它巧妙地將即時通訊軟件的強大功能與Power BI的分析能力相結合。接下來,我們…

MotionSound-簡單易用的文本轉語音工具

本文轉載自:MotionSound-簡單易用的文本轉語音工具 - Hello123工具導航 ** 一、🎯 MotionSound:一鍵讓文字 “開口說話” 的 AI 配音神器 做視頻沒時間配音?PPT 演示想加逼真語音?試試MotionSound吧!它是…

Zynq設備與電腦相連方式

一、Zynq設備通過串口與電腦直接相連 “Zynq設備通過串口與電腦直接相連”是開發和調試Zynq系列SOC(如Zynq-7000或Zynq UltraScale+ MPSoC)時最基礎、最重要的步驟。這個串口連接主要用于: 系統啟動信息輸出:查看Uboot、Linux內核的啟動過程。 系統調試:輸出調試信息(p…

python 邏輯運算練習題

圖書館入館條件檢查題目描述 編寫程序判斷一個人是否能進入圖書館。圖書館有以下入館規則:年齡大于等于 18 歲,或者有家長陪同(無論年齡)輸入示例圖書館入館檢查 請輸入你的年齡:18 是否有家長陪同?(是/否)…

《Java Stream 流從入門到精通:一行代碼搞定集合操作,效率提升 10 倍》

封面圖上流動的「Stream」字樣,正是 Java 8 以來最革命性的特性之一!你是否還在寫冗長的 for 循環遍歷集合?是否為過濾、排序、聚合數據寫一堆重復代碼?Stream 流的出現,以聲明式編程風格將復雜的集合操作濃縮為一行代…

前端筆記2025

前端 與后端交互 下載后端接口的文件時,若是二進制,需要在請求中添加responseType: ‘blob’ 例如 axios.get(‘http://127.0.0.1:8612/api/daily/report/tdjzxz?selectedMonth2022-06’, { headers: { ‘Accesstoken’: ‘f033b94655f84386a0c112b41…

【LeetCode每日一題】226. 翻轉二叉樹 101. 對稱二叉樹

每日一題226. 翻轉二叉樹題目總體思路代碼101. 對稱二叉樹題目總體思路代碼知識點2025.9.5226. 翻轉二叉樹 題目 給你一棵二叉樹的根節點 root ,翻轉這棵二叉樹,并返回其根節點。 示例 1: 輸入:root [4,2,7,1,3,6,9] 輸出&am…

【RNN-LSTM-GRU】第三篇 LSTM門控機制詳解:告別梯度消失,讓神經網絡擁有長期記憶

深入剖析LSTM的三大門控機制:遺忘門、輸入門、輸出門,通過直觀比喻、數學原理和代碼實現,徹底理解如何解決長期依賴問題。1. 引言:為什么需要LSTM?在上一篇講解RNN的文章中,我們了解到??循環神經網絡&…

殘差去噪擴散模型

論文題目:Residual Denoising Diffusion Models(殘差去噪擴散模型) 會議:CVPR2024 摘要:殘差去噪擴散模型(RDDM)是一種新的雙重擴散過程,它將傳統的單一去噪擴散過程解耦為殘差擴散和噪聲擴散。這種雙重擴散框架通過引入殘差,將基于去噪的擴散模型擴展為一種統一的、可…

MySQL與ES索引區別

MySQL與ES索引區別 MySQL索引像字典目錄,ES索引更像整個圖書館的書籍分類系統。 關鍵限制:MySQL單表索引大小影響寫性能,ES的分片數創建后不能改。 比如MySQL的“行”對應ES的“文檔”,MySQL的“表”類似ES的“索引”概念。 MySQL…

vue3圖標終極方案【npm包推薦】vue3-icon-sui(含源碼詳解)

簡介 為徹底實現 vue3 項目圖標自由,特開發此 npm包 vue3-icon-sui,全品類圖標,通通支持! iconify 圖標svg 圖標font-class 圖標 安裝 npm i vue3-icon-sui -S使用 按需導入 任意頁面中 import myIcon from "vue3-icon-su…

redis----持久化

Redis 提供了兩種主要的持久化機制,用于將內存中的數據保存到磁盤,以防止服務器重啟或故障導致數據丟失。這兩種機制分別是 RDB(Redis Database)和 AOF(Append Only File)。1. RDB 持久化RDB 是 Redis 默認…

Docker快速部署Mongodb主副本集實踐

系列文章目錄 第一章 Mongodb的主副本集 文章目錄系列文章目錄前言一、Mongodb基礎介紹數據庫(Database)集合(Collection)文檔(Document)BSON(Binary JSON)_id(主鍵&…

FC平臺安裝Windows Server2016并連接V6存儲

創建 windows server2016 上傳ISO創建虛擬機安裝OS 加載光盤掛載成功之后,重啟虛擬機重啟之后VNC登錄即可。在FC上安裝windows,安裝完成后,必須安裝tools工具,不然沒有虛擬網卡,無法配置ip地址。Windows主機安裝toolsW…

農業XR數字融合工作站,賦能農業專業實踐學習

隨著數字技術與農業的深度融合,農業專業XR數字融合工作站為農業專業學生提供了沉浸式、交互式的學習體驗。農業專業XR數字融合工作站作為集PC、VR、MR技術于一體的軟硬件集成平臺,通過虛擬仿真、數字孿生等技術手段,有效解決了傳統農業教育中…

積分球的使用——簡易版

這篇寫的比較雜。積分球的功能積分球——測量燈具等光源的總光通量、光效、色溫、顯色指數等參數。使用方法1.開啟積分球系統(探測器、光度計、光譜儀),充分預熱(15-30分鐘),使得電子設備穩定,減…

[光學原理與應用-435]:晶體光學 - 晶體的結構-基元/原胞/晶胞/點陣

晶體的結構可通過基元、原胞、晶胞和點陣四個核心概念進行系統描述,它們共同揭示了晶體中原子排列的周期性與對稱性規律,具體如下:1. 基元(Structure Motif)定義:基元是晶體中重復排列的最小結構單元&#…

電腦音頻錄制 | 系統麥克混錄 / 系統聲卡直錄 | 方法匯總 / 常見問題

注:本文為 “電腦音頻錄制 ” 相關合輯。 英文引文,機翻未校。 未整理去重,如有內容異常,請看原文。 How to Record Computer Audio in 6 Free Ways 如何用 6 種免費方式錄制電腦音頻 Sponsored by EaseUS Nov 28, 2023 4:34 a…

2025高教社國賽數學建模競賽B題完整參考論文(含模型和代碼)

2025國賽數學建模競賽B題完整參考論文 目錄 一、 問題重述 1.1 問題背景 1.2 問題回顧與分析 二、 模型假設 三、 符號說明 四、 問題求解與分析 4.1數據預處理 4.2 問題1求解與分析 4.2.1 問題1分析 4.2.2 問題1建模與求解 4.2.3 問題1結果與分析 4.3 問題2求解與分…