现在我们可以用Python代码来创造AI绘画作品。这项技术让我们通过文字描述就能生成各种图片,无论是风景、人物还是抽象艺术。
阿里云百炼提供了强大的图片生成功能,我们可以通过Python代码来调用。
首先安装需要的Python库:
pip install requests dashscope如果使用Python 3,可以用:
pip3 install requests dashscope访问阿里云百炼平台(bailian.console.aliyun.com),注册账号后获取API密钥。这个密钥用来验证我们的请求。
下面是生成图片的基本代码:
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis
import os
# 设置你的API密钥
api_key = "你的API密钥"
# 描述你想要生成的图片
prompt = "一只可爱的橘猫在沙发上睡觉,阳光从窗户照进来,风格温暖明亮"
print('正在生成图片,请稍等...')
result = ImageSynthesis.call(
api_key=api_key,
model="qwen-image", # 使用通义千问图片模型
prompt=prompt, # 图片描述
n=1, # 生成1张图片
size='1024x1024', # 图片尺寸
prompt_extend=True, # 自动扩展提示词
watermark=True # 添加水印
)
# 检查生成结果
if result.status_code == HTTPStatus.OK:
print('图片生成成功!')
# 保存图片到本地
for image in result.output.results:
# 从URL中提取文件名
file_name = PurePosixPath(unquote(urlparse(image.url).path)).parts[-1]
# 下载并保存图片
with open(f'./{file_name}', 'wb+') as file:
image_data = requests.get(image.url).content
file.write(image_data)
print(f'图片已保存为: {file_name}')
else:
print('生成失败,错误信息:')
print(f'状态码: {result.status_code}')
print(f'错误代码: {result.code}')
print(f'错误消息: {result.message}')不同的描述会生成不同风格的图片:
# 风景描述
landscape_prompt = "雪山脚下的湖泊,湖水清澈见底,天空有彩虹,风格写实"
# 人物描述
portrait_prompt = "一位古代中国诗人站在竹林里,手持书卷,水墨画风格"
# 抽象艺术
abstract_prompt = "流动的色彩,蓝色和金色交织,抽象表现主义风格"如果你有性能较好的电脑,可以在本地安装Stable Diffusion来生成图片。
Windows、Mac或Linux系统
Python 3.10.6或更高版本
足够的内存和存储空间
显卡性能越好,生成速度越快
下载Stable Diffusion web UI:
git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git如果无法使用git,可以直接从GitHub下载zip压缩包。
进入项目目录:
cd stable-diffusion-webui下载模型文件:
访问Hugging Face网站下载模型
将下载的模型文件放到models/Stable-diffusion文件夹
启动程序:
在Windows上:
webui-user.bat在Linux或Mac上:
./webui.sh启动成功后,在浏览器打开 http://127.0.0.1:7860 就能看到操作界面。
如果你希望通过代码调用,可以这样设置:
import requests
import json
def generate_local_image(prompt, negative_prompt="", steps=20):
"""
调用本地Stable Diffusion生成图片
"""
url = "http://127.0.0.1:7860/sdapi/v1/txt2img"
payload = {
"prompt": prompt,
"negative_prompt": negative_prompt,
"steps": steps,
"width": 512,
"height": 512,
"cfg_scale": 7,
"sampler_name": "Euler a"
}
try:
response = requests.post(url, json=payload)
result = response.json()
# 保存图片
if 'images' in result:
import base64
from io import BytesIO
from PIL import Image
image_data = base64.b64decode(result['images'][0])
image = Image.open(BytesIO(image_data))
image.save('generated_image.png')
print("图片生成成功!")
else:
print("生成失败")
except Exception as e:
print(f"错误: {e}")
# 使用示例
generate_local_image("一只在花园里追逐蝴蝶的柯基犬")好的描述能生成更好的图片:
# 基础结构:主题 + 环境 + 风格 + 细节
# 示例1:人物
good_prompt1 = "一位穿着汉服的少女在樱花树下弹古筝,阳光透过花瓣,唯美动漫风格,细节精致"
# 示例2:建筑
good_prompt2 = "未来主义城市,高楼大厦有悬浮车道,夜晚霓虹灯闪烁,赛博朋克风格"
# 示例3:动物
good_prompt3 = "北极熊妈妈带着幼崽在冰川上,极光背景,写实摄影风格,细节清晰"告诉AI不希望图片中出现什么:
negative_prompt = "模糊,变形,多余的手指,丑陋,水印,文字"如果需要生成多张图片,可以使用循环:
from dashscope import ImageSynthesis
import time
def batch_generate_images(prompts_list, api_key):
"""
批量生成多张图片
"""
generated_files = []
for i, prompt in enumerate(prompts_list):
print(f'正在生成第{i+1}张图片: {prompt[:30]}...')
try:
result = ImageSynthesis.call(
api_key=api_key,
model="qwen-image",
prompt=prompt,
n=1,
size='1024x1024'
)
if result.status_code == 200:
# 保存图片(这里需要添加保存代码)
filename = f'batch_image_{i+1}.png'
generated_files.append(filename)
print(f'第{i+1}张图片生成成功')
else:
print(f'第{i+1}张图片生成失败')
# 避免请求过于频繁
time.sleep(2)
except Exception as e:
print(f'生成第{i+1}张图片时出错: {e}')
return generated_files
# 使用示例
prompts = [
"清晨的森林,雾气缭绕,阳光穿透树叶",
"夜晚的城市天际线,灯火通明",
"沙漠中的绿洲,棕榈树和湖泊"
]
# batch_generate_images(prompts, "你的API密钥")通过调整参数控制图片风格:
def generate_with_style(prompt, style_description, api_key):
"""
生成特定风格的图片
"""
full_prompt = f"{prompt},{style_description}"
result = ImageSynthesis.call(
api_key=api_key,
model="qwen-image",
prompt=full_prompt,
n=1,
size='1024x1024'
)
return result
# 不同风格示例
styles = {
"水墨画": "中国传统水墨画风格,黑白灰调,留白",
"油画": "古典油画风格,厚重笔触,丰富色彩",
"卡通": "日系动漫风格,大眼睛,色彩鲜艳",
"写实": "摄影写实风格,细节精确,真实感强"
}
# 生成不同风格的同一主题
theme = "一只猫在窗台上"
for style_name, style_desc in styles.items():
print(f"生成{style_name}风格...")
# generate_with_style(theme, style_desc, "你的API密钥")在实际使用中可能会遇到问题,这里提供一些解决方法:
def safe_image_generation(prompt, api_key, max_retries=3):
"""
带错误处理的图片生成函数
"""
for attempt in range(max_retries):
try:
result = ImageSynthesis.call(
api_key=api_key,
model="qwen-image",
prompt=prompt,
n=1,
size='1024x1024'
)
if result.status_code == 200:
return result
else:
print(f"尝试{attempt+1}失败: {result.message}")
if attempt < max_retries - 1:
print("等待后重试...")
time.sleep(5)
except Exception as e:
print(f"尝试{attempt+1}出现异常: {e}")
if attempt < max_retries - 1:
time.sleep(5)
print("所有尝试都失败了")
return None使用API服务时要注意控制费用:
class AIImageGenerator:
def __init__(self, api_key, monthly_budget=100):
self.api_key = api_key
self.monthly_budget = monthly_budget
self.used_count = 0
self.max_requests = monthly_budget # 假设每次请求1元
def can_generate(self):
return self.used_count < self.max_requests
def generate_image(self, prompt):
if not self.can_generate():
print("已达到本月生成限额")
return None
result = ImageSynthesis.call(
api_key=self.api_key,
model="qwen-image",
prompt=prompt,
n=1,
size='1024x1024'
)
if result.status_code == 200:
self.used_count += 1
print(f"本月已使用 {self.used_count}/{self.max_requests} 次")
return result
# 使用示例
# generator = AIImageGenerator("你的API密钥", 50) # 每月50次限额
# result = generator.generate_image("测试图片")AI绘画为创作者提供了强大的工具。通过Python代码,我们可以:
使用云服务API快速生成图片
在本地部署Stable Diffusion获得更多控制权
批量生成多种风格的图片
通过调整提示词获得理想的效果
主要步骤:
安装必要的Python库
获取API密钥或设置本地环境
编写有效的图片描述
处理生成结果和错误
对于初学者,建议先从阿里云百炼开始,使用简单且不需要强大的硬件。有经验的用户可以尝试本地部署Stable Diffusion,获得更多自定义选项。
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!