def batch_edit_images(edit_tasks):
"""批量编辑图片"""
results = []
for task in edit_tasks:
try:
print(f"正在编辑: {task['image_path']}")
print(f"编辑指令: {task['prompt']}")
edited_url = edit_local_image(
image_path=task['image_path'],
prompt=task['prompt'],
aspect_ratio=task.get('aspect_ratio', '1:1'),
mask_path=task.get('mask_path')
)
if edited_url:
# 下载编辑后的图片
filename = save_edited_image(edited_url, task['image_path'])
results.append({
'original': task['image_path'],
'prompt': task['prompt'],
'edited_url': edited_url,
'saved_file': filename,
'success': True
})
else:
results.append({
'original': task['image_path'],
'prompt': task['prompt'],
'success': False,
'error': 'API 调用失败'
})
except Exception as e:
results.append({
'original': task['image_path'],
'prompt': task['prompt'],
'success': False,
'error': str(e)
})
return results
def save_edited_image(url, original_path):
"""保存编辑后的图片"""
import time
response = requests.get(url)
if response.status_code == 200:
# 生成新文件名
base_name = os.path.splitext(os.path.basename(original_path))[0]
timestamp = int(time.time())
filename = f"{base_name}_edited_{timestamp}.png"
with open(filename, 'wb') as f:
f.write(response.content)
print(f"已保存: {filename}")
return filename
return None
# 批量编辑示例
edit_tasks = [
{
'image_path': 'photo1.jpg',
'prompt': 'Change the sky to a dramatic stormy sky',
'aspect_ratio': '3:2'
},
{
'image_path': 'photo2.jpg',
'prompt': 'Remove all people from the image',
'aspect_ratio': '16:9',
'mask_path': 'mask2.png'
},
{
'image_path': 'photo3.jpg',
'prompt': 'Make the image look like a vintage photograph',
'aspect_ratio': '1:1'
}
]
results = batch_edit_images(edit_tasks)
# 输出结果
for result in results:
if result['success']:
print(f"✅ {result['original']} -> {result['saved_file']}")
else:
print(f"❌ {result['original']} -> {result['error']}")