Gemini 提供了一个强大的接口,可以实现文生图(Text-to-Image)功能,让你能够通过简单的文本描述生成高质量的图像。本文将详细介绍如何利用 Gemini 接口在本地实现文生图功能,并将生成的图片保存到本地。
核心功能与优势
- 图片和代码均在本地:所有操作都在本地完成。
- 免费:Gemini 虽然是Google的商业模型,但是亲测可以免费使用。
- 灵活定制:通过编写不同的提示词,可以生成各种风格和主题的图像。
代码很简单,主要就是两部分:请求Gemini接口和解析接口返回的图像数据。
注意把api key换成自己的,如果没有的在
https://aistudio.google.com/app/apikey 这里注册。,推荐使用gemini-2.0-flash-exp这个模型,然后编写自己的提示词。请求Gemini API。
拿到返回的数据后解析一下,指定一下目录和文件名,保存到本地。我这里生了一个小飞机,查看一下生成的图片,效果还是不错的。
以下是完整代码:
from google import genai
from google.genai import types
from PIL import Image
import io
import base64
import os
client = genai.Client(api_key="xxxxxxx")
model = 'gemini-2.0-flash-exp'
response = client.models.generate_content(
model=model,
# 文生图提示词
contents='Generate a sleek, futuristic fighter jet with a transparent background, perfect for a vertical scrolling shooter game. The jet should have a streamlined design with glowing blue thrusters and neon accents. It should be rendered in high resolution with a transparent background to ensure it can be seamlessly integrated into various game environments. The jet should have a metallic finish with intricate details, giving it a high-tech and stylish appearance',
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_data = base64.b64decode(part.inline_data.data)
# 图片保存路径和文件名
filepath = os.path.join("D:/workspaces/img", "2.png")
# 保存图片到文件
with open(filepath, "wb") as f:
f.write(image_data)
print(f"图片已保存到: {filepath}")