对接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求解与分…