用 AI 自动生成网站封面图:Pollinations.ai 实战记录

前言

之前写博客时,每次都要手动找封面图或者自己用 Photoshop 做,挺耗时间的。后来发现了 Pollinations.ai 这个免费的 AI 图片生成 API,决定把它集成到博客工作流里。

这篇文章完整记录了我怎么把 Pollinations.ai 用到博客封面图生成中的全过程,包括踩过的坑、优化策略和成本分析。

为什么选 Pollinations.ai?

我对比了几个主流的 AI 图片生成 API:

服务商 免费额度 价格 支持风格 需要API Key
DALL-E 3 $0.04/图
Stable Diffusion (via API) $0.002/图 丰富
Midjourney 有限 $10/月订阅 风格独特 ❌ (Discord)
Pollinations.ai 无限制免费 免费 主流模型 不需要

Pollinations.ai 的优势很明显:

1. 完全免费,无需注册

不需要 API Key,直接 GET 请求就能用,这对我这种个人博客来说最友好。

2. 支持多种主流模型

  • Flux (默认,质量高)
  • Stable Diffusion 1.5/2.1/XL
  • DALL-E Mini
  • 还有一些二次元模型

3. 参数灵活

  • 支持宽高比自定义
  • 支持随机种子控制
  • 支持提示词增强和否定提示词

4. 响应速度快

大部分请求 2-3 秒内返回图片,适合批量生成。

基础 API 调用

最简单的调用方式

1
2
3
4
5
6
7
8
9
10
11
12
import requests

def generate_image(prompt: str, filename: str):
url = f"https://gen.pollinations.ai/image/{prompt}"
response = requests.get(url)

if response.status_code == 200:
with open(filename, 'wb') as f:
f.write(response.content)
print(f"✅ 图片已保存: {filename}")
else:
print(f"❌ 生成失败: {response.status_code}")

调用示例:

1
2
3
4
generate_image(
"a person working at minimal clean desk with laptop open, soft warm morning light through window",
"workspace-cover.jpg"
)

带参数的调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
def generate_image(
prompt: str,
filename: str,
width: int = 1200,
height: int = 630,
model: str = "flux",
seed: int = None,
nologo: bool = True
):
url = f"https://gen.pollinations.ai/image/{prompt}"
params = {
'width': width,
'height': height,
'model': model,
'nologo': 'true' if nologo else 'false'
}

if seed:
params['seed'] = seed

response = requests.get(url, params=params)

if response.status_code == 200:
with open(filename, 'wb') as f:
f.write(response.content)
print(f"✅ 图片已保存: {filename}")
else:
print(f"❌ 生成失败: {response.status_code}")

我的生成脚本 generate_image.py

为了方便博客使用,我写了一个命令行脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/usr/bin/env python3
"""
博客封面图生成脚本 - 基于 Pollinations.ai API
"""

import argparse
import requests
from pathlib import Path
from urllib.parse import quote

# 配置
DEFAULT_MODEL = "flux"
DEFAULT_WIDTH = 1200
DEFAULT_HEIGHT = 630
BLOG_IMAGES_DIR = Path("blog/source/img")
API_BASE_URL = "https://gen.pollinations.ai/image"

def generate_image(
prompt: str,
filename: str,
width: int = DEFAULT_WIDTH,
height: int = DEFAULT_HEIGHT,
model: str = DEFAULT_MODEL,
seed: int = None
):
"""生成图片并保存到博客图片目录"""

# 确保目录存在
BLOG_IMAGES_DIR.mkdir(parents=True, exist_ok=True)

# 构建 URL
encoded_prompt = quote(prompt)
url = f"{API_BASE_URL}/{encoded_prompt}"

# 参数
params = {
'width': width,
'height': height,
'model': model,
'nologo': 'true'
}

if seed is not None:
params['seed'] = seed

# 请求
try:
response = requests.get(url, params=params, timeout=30)
response.raise_for_status()

# 保存
output_path = BLOG_IMAGES_DIR / filename
with open(output_path, 'wb') as f:
f.write(response.content)

file_size = output_path.stat().st_size / 1024 # KB

print(f"[INFO] 图片已生成并保存")
print(f" Prompt: {prompt[:100]}...")
print(f" Model: {model}")
print(f" Size: {width}x{height}")
print(f" Seed: {seed if seed else 'random'}")
print(f" File size: {file_size:.1f} KB")
print(f" Path: {output_path}")
print(f" Markdown: ![](/img/{filename})")

return True

except requests.exceptions.RequestException as e:
print(f"[ERROR] 生成失败: {e}")
return False

def main():
parser = argparse.ArgumentParser(description='生成博客封面图')
parser.add_argument('prompt', help='图片描述提示词')
parser.add_argument('filename', help='输出文件名(不带路径)')
parser.add_argument('--width', type=int, default=DEFAULT_WIDTH,
help=f'图片宽度,默认 {DEFAULT_WIDTH}')
parser.add_argument('--height', type=int, default=DEFAULT_HEIGHT,
help=f'图片高度,默认 {DEFAULT_HEIGHT}')
parser.add_argument('--model', type=str, default=DEFAULT_MODEL,
help=f'AI模型,默认 {DEFAULT_MODEL}')
parser.add_argument('--seed', type=int, help='随机种子(可选)')

args = parser.parse_args()

generate_image(
prompt=args.prompt,
filename=args.filename,
width=args.width,
height=args.height,
model=args.model,
seed=args.seed
)

if __name__ == '__main__':
main()

使用示例

1
2
3
4
5
6
7
8
# 基础用法
python generate_image.py "workspace with laptop and notebook" workspace.jpg

# 指定宽高
python generate_image.py "workspace scene" workspace.jpg --width 800 --height 600

# 指定模型和种子
python generate_image.py "workspace scene" workspace.jpg --model flux --seed 12345

提示词优化策略

一开始用简单的英文提示词,效果不太稳定。后来总结了一套优化策略:

1. 结构化提示词

1
主体描述 + 环境细节 + 艺术风格 + 技术参数 + 排除项

示例:

1
2
3
4
5
6
7
8
9
主体描述:a person working at a minimal clean desk with laptop open

环境细节:soft warm morning light through window, coffee mug and notebook nearby

艺术风格:flat design illustration, muted warm colors

技术参数:high quality, 4k

排除项:no text, no logo, no watermark

2. 不同类型文章的提示词模板

工作场景类(工具指南、方法论)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
workspace_prompt = (
"a person working at {activity}, "
"minimal clean desk with laptop open, "
"soft warm morning light through window, "
"{accessories}, "
"calm productive atmosphere, "
"flat design illustration, "
"muted warm colors, "
"no text, no logo, no watermark"
)

# 使用示例
workspace_prompt.format(
activity="typing on laptop",
accessories="coffee mug and notebook nearby"
)

数据图表类(方法论、AI周报)

1
2
3
4
5
6
7
8
9
10
11
12
13
infographic_prompt = (
"abstract data visualization showing {concept}, "
"infographic style, clean design, "
"{color_scheme} colors, "
"professional, modern, "
"no text, no logo, no watermark"
)

# 使用示例
infographic_prompt.format(
concept="AI writing workflow",
color_scheme="blue and purple"
)

新闻拼贴类(AI周报)

1
2
3
4
5
6
7
8
9
10
11
12
13
news_collage_prompt = (
"news collage style layout, "
"{elements}, "
"tech elements, calendar design, "
"information density but readable, "
"medium saturation, "
"no text, no logo, no watermark"
)

# 使用示例
news_collage_prompt.format(
elements="AI robots, data charts, code snippets"
)

界面展示类(工具评测、实战记录)

1
2
3
4
5
6
7
8
9
10
11
12
13
ui_comparison_prompt = (
"multiple screen interfaces side by side, "
"{app_names} comparison, "
"clean modern UI design, "
"professional style, "
"highlighted differences, "
"no text, no logo, no watermark"
)

# 使用示例
ui_comparison_prompt.format(
app_names="Claude, GPT-4, DeepSeek"
)

3. 提示词增强技巧

使用英文提示词

虽然 Pollinations.ai 支持中文,但英文提示词效果更好:

1
2
3
4
5
# ❌ 中文提示词(效果不稳定)
"一个人在干净的桌子前工作,笔记本电脑,温暖的晨光"

# ✅ 英文提示词(效果稳定)
"a person working at a minimal clean desk with laptop open, soft warm morning light through window"

添加风格关键词

根据想要的风格添加关键词:

1
2
3
4
5
6
7
8
9
10
11
# 极简风格
"minimalist, clean, simple, uncluttered"

# 扁平插画风格
"flat design illustration, vector art, 2D"

# 写实风格
"photorealistic, 8k, high detail, realistic"

# 手绘风格
"hand-drawn, sketch, pencil drawing, artistic"

控制画面元素

1
2
3
4
5
6
7
8
# 明确排除不需要的元素
"no text, no logo, no watermark, no people (if not needed)"

# 限制画面元素数量
"minimal elements, clean composition"

# 控制色调
"muted colors" / "vibrant colors" / "monochrome"

批量生成策略

有时候需要生成多个备选图片,然后选择最好的一个。

方法 1:使用随机种子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import random

def generate_variants(prompt, filename_prefix, count=3):
"""生成多个变体"""
for i in range(count):
seed = random.randint(1000, 9999)
filename = f"{filename_prefix}_{i+1}.jpg"
generate_image(prompt, filename, seed=seed)

# 使用
generate_variants(
"workspace scene",
"workspace_variant",
count=3
)

方法 2:使用不同的提示词变体

1
2
3
4
5
6
7
8
9
prompt_variants = [
"workspace with laptop, warm light, flat illustration",
"person working at desk, morning sun, minimal design",
"clean workspace, laptop and coffee, soft lighting"
]

for i, prompt in enumerate(prompt_variants):
filename = f"workspace_variant_{i+1}.jpg"
generate_image(prompt, filename)

方法 3:使用不同的模型

1
2
3
4
5
models = ["flux", "stable-diffusion", "dalle-mini"]

for i, model in enumerate(models):
filename = f"workspace_{model}.jpg"
generate_image(prompt, filename, model=model)

成本分析

调用成本

项目 成本
API 调用 免费
带宽消耗 几乎可忽略(单张图 ~200KB)
存储空间 200KB/图,10 篇文章 = 2MB

结论: 对于个人博客,成本几乎为零。

时间成本

  • 单张图生成:2-3 秒
  • 提示词编写:30-60 秒
  • 筛选和微调:1-2 分钟

单篇图片总耗时: 约 2-3 分钟

对比:

方式 时间成本 质量稳定性
手动搜索图库 5-10 分钟 高(但需要筛选)
PS 自己做 20-30 分钟 极高(需要设计技能)
Pollinations.ai 2-3 分钟 中高(需优化提示词)

踩坑记录

坑 1:中文提示词效果不稳定

问题: 早期用中文提示词,生成的图片经常不符合预期。

解决: 改用英文提示词,效果大幅提升。如果习惯用中文,可以用翻译工具转成英文后再调用 API。

坑 2:图片质量波动大

问题: 同样的提示词,有时生成高质量图片,有时效果很差。

解决:

  1. 使用固定种子控制随机性
  2. 添加更多质量关键词:”high quality, 4k, detailed”
  3. 多生成几个版本,选择最好的

坑 3:尺寸问题

问题: 生成的图片有时不符合博客封面图要求的宽高比。

解决:

  1. 明确指定宽高参数:--width 1200 --height 630
  2. 使用 nologo=true 避免 API 自动添加水印导致尺寸变化

坑 4:生成速度慢

问题: 有时候请求会卡住或超时。

解决:

  1. 设置合理的超时时间:timeout=30
  2. 添加重试机制
  3. 避免并发过多请求(虽然免费,但服务器会限流)

坑 5:提示词被截断

问题: 提示词太长,URL 会超出浏览器或 HTTP 客户端的限制。

解决:

  1. 保持提示词简洁
  2. 使用 URL 编码(Python 的 urllib.parse.quote
  3. 必要时使用 POST 请求而不是 GET

高级技巧

1. 自动根据文章内容生成提示词

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def generate_prompt_from_article(article_content: str, article_type: str) -> str:
"""根据文章内容和类型自动生成提示词"""

# 提取关键词(简单实现)
keywords = extract_keywords(article_content)[:5]

# 根据文章类型选择模板
if article_type == "tool-guide":
return workspace_prompt.format(activity=", ".join(keywords))
elif article_type == "infographic":
return infographic_prompt.format(concept=", ".join(keywords))
# ... 其他类型

return "minimalist design, clean composition"

2. 集成到博客工作流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Hexo 脚本示例(生成新文章时自动创建封面图)
import os

def hexo_on_new_post(post_filename: str):
"""Hexo 新文章时的钩子"""

# 读取文章
with open(post_filename, 'r', encoding='utf-8') as f:
content = f.read()

# 提取元数据
title = extract_title(content)
article_type = extract_type(content)

# 生成提示词
prompt = generate_prompt_from_article(content, article_type)

# 生成封面图
filename = f"{slugify(title)}.jpg"
generate_image(prompt, filename)

# 更新文章元数据
update_index_img(post_filename, f"/img/{filename}")

3. 使用种子保证可重复性

1
2
3
4
5
6
7
8
9
10
11
12
13
# 使用文章日期或标题哈希作为种子
import hashlib

def get_seed_from_article(article_title: str, article_date: str) -> int:
"""根据文章标题和日期生成固定种子"""

combined = f"{article_title}_{article_date}"
hash_value = int(hashlib.md5(combined.encode()).hexdigest()[:8], 16)
return hash_value % 10000 # 限制在 4 位数内

# 这样每次重新生成都会得到相同的图片
seed = get_seed_from_article(article_title, "2026-03-21")
generate_image(prompt, filename, seed=seed)

局限性

虽然 Pollinations.ai 很好用,但也有一些局限性:

1. 质量不如付费服务

与 DALL-E 3、Midjourney 相比,细节和创意能力还是差一些。

2. 不支持复杂的控制

像 Stable Diffusion 的 ControlNet 那样精确控制构图、姿态的能力是没有的。

3. 免费服务的限制

  • 可能有并发限制
  • 响应速度不如付费服务稳定
  • 不提供商业使用的明确保证

4. 版权问题

生成图片的版权归属不明确,不适合需要明确版权授权的商业项目。

替代方案

如果 Pollinations.ai 不满足需求,可以考虑:

1. Stable Diffusion 本地部署

优点:

  • 完全免费,无调用限制
  • 可以使用 ControlNet 等高级功能
  • 完全控制模型和参数

缺点:

  • 需要较好的显卡(至少 8GB 显存)
  • 安装配置较复杂
  • 需要一定的技术能力

2. Replicate API

优点:

  • 集成了多种模型(包括 Flux、SDXL)
  • 按使用付费,成本可控
  • 有稳定的服务和 API

缺点:

  • 需要付费(约 $0.002/图)
  • 需要注册账号

3. 自托管 Stable Diffusion WebUI

优点:

  • 完全控制
  • 可以本地优化和定制
  • 支持各种插件和扩展

缺点:

  • 需要服务器资源
  • 需要维护

下一步优化计划

目前这个自动生成封面图的方案已经基本满足需求,接下来打算:

  1. 优化提示词模板:针对不同文章类型进一步细化
  2. 集成到 CI/CD:在文章生成时自动创建封面图
  3. 添加质量评估:自动筛选质量较高的图片
  4. 多模型混合使用:根据文章类型选择最合适的模型

结语

Pollinations.ai 作为免费的 AI 图片生成 API,对个人博客来说是一个非常实用的工具。虽然它有一些局限性,但对于博客封面图这种场景,完全够用。

关键是要掌握好提示词的优化技巧,形成自己的风格指南。一旦建立了稳定的工作流,就能大幅提升内容创作的效率。

希望这篇文章的实战经验对你有帮助。如果你也在用 Pollinations.ai 或者其他 AI 图片生成工具,欢迎交流经验!


相关文章:


用 AI 自动生成网站封面图:Pollinations.ai 实战记录
https://www.ohtudou.top/2026/03/21/2026-03-21-ai-lab-pollinations-ai/
作者
Tudo
发布于
2026年3月21日
许可协议