WuliArt Qwen-Image Turbo保姆级教程:生成图EXIF信息写入与版权水印添加
WuliArt Qwen-Image Turbo保姆级教程:生成图EXIF信息写入与版权水印添加
本文阅读时间约15分钟,包含详细操作步骤和完整代码示例
1. 项目简介
WuliArt Qwen-Image Turbo是一款专为个人GPU环境优化的高性能文生图系统。这个项目基于阿里通义千问的Qwen-Image-2512模型底座,结合了专门优化的Wuli-Art Turbo LoRA微调权重,在保持高质量图像生成的同时,大幅提升了生成速度。
系统采用多项技术创新:原生支持BFloat16精度避免生成黑图,仅需4步推理即可完成高清图像生成,显存优化让24G显存也能流畅运行。默认输出1024×1024分辨率的JPEG格式图像,画质达到95%高质量标准。
本文将重点介绍如何在生成的图像中自动添加EXIF元数据和版权水印,保护您的创作成果。
2. 环境准备与安装
在开始添加EXIF信息和水印功能前,确保你已经成功部署了WuliArt Qwen-Image Turbo系统。如果尚未安装,以下是快速安装步骤:
# 克隆项目仓库
git clone https://github.com/your-repo/wuliart-qwen-image-turbo.git
cd wuliart-qwen-image-turbo
# 创建Python虚拟环境
python -m venv venv
source venv/bin/activate # Linux/Mac
# 或 venv\Scripts\activate # Windows
# 安装依赖包
pip install -r requirements.txt
# 安装额外的图像处理库
pip install Pillow piexif
安装完成后,确认以下库已正确安装:
- Pillow:用于图像处理和水印添加
- piexif:用于EXIF元数据读写
- 其他核心依赖:torch, transformers等
3. EXIF信息写入功能实现
EXIF(Exchangeable Image File Format)是图像文件中存储元数据的标准格式。为生成的图像添加EXIF信息可以帮助保护版权、记录创作信息。
3.1 基础EXIF信息写入
首先创建一个Python脚本来处理EXIF信息添加:
import piexif
from PIL import Image
import json
from datetime import datetime
def add_exif_metadata(image_path, prompt, author="Your Name", copyright_info="All rights reserved"):
"""
为图像添加EXIF元数据
参数:
image_path: 图像文件路径
prompt: 生成图像使用的提示词
author: 作者信息
copyright_info: 版权信息
"""
try:
# 加载图像
image = Image.open(image_path)
# 准备EXIF数据
exif_dict = {
"0th": {},
"Exif": {},
"GPS": {},
"1st": {},
"thumbnail": None
}
# 添加基本元数据
exif_dict["0th"][piexif.ImageIFD.Artist] = author.encode('utf-8')
exif_dict["0th"][piexif.ImageIFD.Copyright] = copyright_info.encode('utf-8')
exif_dict["0th"][piexif.ImageIFD.ImageDescription] = f"Generated with WuliArt Qwen-Image Turbo. Prompt: {prompt}".encode('utf-8')
# 添加生成时间
current_time = datetime.now().strftime("%Y:%m:%d %H:%M:%S")
exif_dict["Exif"][piexif.ExifIFD.DateTimeOriginal] = current_time.encode('utf-8')
exif_dict["Exif"][piexif.ExifIFD.DateTimeDigitized] = current_time.encode('utf-8')
# 添加软件信息
exif_dict["0th"][piexif.ImageIFD.Software] = "WuliArt Qwen-Image Turbo".encode('utf-8')
# 转换为EXIF字节数据
exif_bytes = piexif.dump(exif_dict)
# 保存图像并保留EXIF数据
image.save(image_path, "JPEG", exif=exif_bytes, quality=95)
print(f"EXIF信息已成功添加到 {image_path}")
except Exception as e:
print(f"添加EXIF信息时出错: {str(e)}")
# 使用示例
if __name__ == "__main__":
add_exif_metadata("generated_image.jpg",
"Cyberpunk street, neon lights, rain",
"Your Name",
"© 2024 Your Name. All rights reserved.")
3.2 高级EXIF信息定制
对于更专业的用途,可以添加更多详细的EXIF信息:
def add_detailed_exif_metadata(image_path, prompt, author, copyright_info, additional_metadata=None):
"""
添加详细的EXIF元数据
参数:
image_path: 图像文件路径
prompt: 生成提示词
author: 作者信息
copyright_info: 版权信息
additional_metadata: 额外的元数据字典
"""
# 基础EXIF添加
add_exif_metadata(image_path, prompt, author, copyright_info)
# 添加额外元数据
if additional_metadata:
image = Image.open(image_path)
exif_dict = piexif.load(image.info.get("exif", b""))
# 添加自定义元数据(使用UserComment字段)
custom_data = {
"generation_prompt": prompt,
"model": "WuliArt Qwen-Image Turbo",
"generation_date": datetime.now().isoformat(),
**additional_metadata
}
exif_dict["Exif"][piexif.ExifIFD.UserComment] = json.dumps(custom_data).encode('utf-8')
# 保存更新后的EXIF数据
exif_bytes = piexif.dump(exif_dict)
image.save(image_path, "JPEG", exif=exif_bytes, quality=95)
4. 版权水印添加功能
水印是保护图像版权的有效方式。以下是几种不同的水印添加方法:
4.1 文字水印添加
from PIL import Image, ImageDraw, ImageFont
def add_text_watermark(image_path, watermark_text, output_path=None, position="bottom-right"):
"""
为图像添加文字水印
参数:
image_path: 原始图像路径
watermark_text: 水印文字
output_path: 输出路径(可选)
position: 水印位置(bottom-right, bottom-left, top-right, top-left, center)
"""
if output_path is None:
output_path = image_path
try:
# 打开图像
image = Image.open(image_path)
# 创建绘图对象
draw = ImageDraw.Draw(image)
# 尝试加载字体,如果失败则使用默认字体
try:
font = ImageFont.truetype("arial.ttf", 20)
except:
font = ImageFont.load_default()
# 计算文字尺寸和位置
text_bbox = draw.textbbox((0, 0), watermark_text, font=font)
text_width = text_bbox[2] - text_bbox[0]
text_height = text_bbox[3] - text_bbox[1]
# 设置水印位置
margin = 20
if position == "bottom-right":
x = image.width - text_width - margin
y = image.height - text_height - margin
elif position == "bottom-left":
x = margin
y = image.height - text_height - margin
elif position == "top-right":
x = image.width - text_width - margin
y = margin
elif position == "top-left":
x = margin
y = margin
else: # center
x = (image.width - text_width) // 2
y = (image.height - text_height) // 2
# 添加文字背景(半透明)
background_bbox = (x-5, y-5, x + text_width + 5, y + text_height + 5)
draw.rectangle(background_bbox, fill=(0, 0, 0, 128))
# 添加文字水印
draw.text((x, y), watermark_text, font=font, fill=(255, 255, 255, 200))
# 保存图像
image.save(output_path, "JPEG", quality=95)
print(f"文字水印已添加到 {output_path}")
except Exception as e:
print(f"添加文字水印时出错: {str(e)}")
4.2 图片Logo水印添加
def add_image_watermark(input_image_path, watermark_image_path, output_path=None, opacity=0.3, position="bottom-right"):
"""
为图像添加图片Logo水印
参数:
input_image_path: 原始图像路径
watermark_image_path: 水印图片路径
output_path: 输出路径(可选)
opacity: 水印透明度(0.0-1.0)
position: 水印位置
"""
if output_path is None:
output_path = input_image_path
try:
# 打开原始图像和水印图像
base_image = Image.open(input_image_path).convert("RGBA")
watermark = Image.open(watermark_image_path).convert("RGBA")
# 调整水印大小(最大宽度为原始图像的20%)
max_size = int(base_image.width * 0.2)
watermark_ratio = watermark.width / watermark.height
new_width = min(watermark.width, max_size)
new_height = int(new_width / watermark_ratio)
watermark = watermark.resize((new_width, new_height), Image.Resampling.LANCZOS)
# 调整水印透明度
alpha = watermark.split()[3]
alpha = alpha.point(lambda p: p * opacity)
watermark.putalpha(alpha)
# 设置水印位置
margin = 20
if position == "bottom-right":
x = base_image.width - watermark.width - margin
y = base_image.height - watermark.height - margin
elif position == "bottom-left":
x = margin
y = base_image.height - watermark.height - margin
elif position == "top-right":
x = base_image.width - watermark.width - margin
y = margin
elif position == "top-left":
x = margin
y = margin
else: # center
x = (base_image.width - watermark.width) // 2
y = (base_image.height - watermark.height) // 2
# 合并图像
base_image.paste(watermark, (x, y), watermark)
# 转换回RGB模式并保存
base_image = base_image.convert("RGB")
base_image.save(output_path, "JPEG", quality=95)
print(f"图片水印已添加到 {output_path}")
except Exception as e:
print(f"添加图片水印时出错: {str(e)}")
5. 集成到WuliArt生成流程
现在我们将EXIF和水印功能集成到WuliArt的图像生成流程中:
5.1 创建完整的后处理脚本
import os
from datetime import datetime
def process_generated_image(image_path, prompt, author, copyright_text,
add_watermark=True, watermark_text=None,
watermark_image_path=None, output_dir="output"):
"""
完整的图像后处理流程:EXIF添加 + 水印添加
参数:
image_path: 生成的图像路径
prompt: 生成提示词
author: 作者信息
copyright_text: 版权信息
add_watermark: 是否添加水印
watermark_text: 文字水印内容
watermark_image_path: 图片水印路径
output_dir: 输出目录
"""
# 确保输出目录存在
os.makedirs(output_dir, exist_ok=True)
# 生成输出文件名(带时间戳)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
base_name = os.path.basename(image_path)
name_without_ext = os.path.splitext(base_name)[0]
output_filename = f"{name_without_ext}_{timestamp}.jpg"
output_path = os.path.join(output_dir, output_filename)
# 复制原始图像到输出路径
from shutil import copy2
copy2(image_path, output_path)
# 添加EXIF信息
add_exif_metadata(output_path, prompt, author, copyright_text)
# 添加水印(如果启用)
if add_watermark:
if watermark_text:
add_text_watermark(output_path, watermark_text, output_path)
elif watermark_image_path and os.path.exists(watermark_image_path):
add_image_watermark(output_path, watermark_image_path, output_path)
print(f"图像处理完成: {output_path}")
return output_path
# 配置参数(根据实际需求修改)
CONFIG = {
"author": "您的名字",
"copyright_text": "© 2024 您的名字. 保留所有权利。",
"watermark_text": "© 您的名字 - 生成于WuliArt",
"watermark_image_path": None, # 设置为None使用文字水印,或提供图片路径
"output_directory": "processed_images"
}
# 使用示例
def example_usage():
# 假设这是WuliArt生成的图像
generated_image = "path/to/generated/image.jpg"
prompt = "Cyberpunk street, neon lights, rain, reflection, 8k masterpiece"
# 处理后处理
processed_image = process_generated_image(
image_path=generated_image,
prompt=prompt,
author=CONFIG["author"],
copyright_text=CONFIG["copyright_text"],
add_watermark=True,
watermark_text=CONFIG["watermark_text"],
watermark_image_path=CONFIG["watermark_image_path"],
output_dir=CONFIG["output_directory"]
)
print(f"最终图像已保存至: {processed_image}")
5.2 自动化集成方案
要将后处理功能自动集成到WuliArt生成流程中,你需要修改生成脚本,在图像生成完成后自动调用后处理函数:
# 在WuliArt生成脚本的适当位置添加以下代码
# 图像生成完成后,添加后处理调用
def generate_image_callback(generated_image_path, prompt):
"""
WuliArt生成完成后的回调函数
"""
try:
# 你的配置
config = {
"author": "你的名字",
"copyright_text": "© 2024 你的名字 - 保留所有权利",
"watermark_text": "生成于WuliArt Qwen-Image Turbo",
"output_directory": "watermarked_images"
}
# 处理后处理
final_image = process_generated_image(
image_path=generated_image_path,
prompt=prompt,
author=config["author"],
copyright_text=config["copyright_text"],
add_watermark=True,
watermark_text=config["watermark_text"],
output_dir=config["output_directory"]
)
print(f"✅ 图像生成和后处理完成: {final_image}")
return final_image
except Exception as e:
print(f"❌ 后处理过程中出错: {str(e)}")
return generated_image_path # 返回原始图像
# 在WuliArt生成函数调用后添加回调
# generated_image = your_wuliart_generate_function(prompt)
# processed_image = generate_image_callback(generated_image, prompt)
6. 验证与测试
完成集成后,建议进行全面的测试来验证功能是否正常工作:
6.1 EXIF信息验证测试
def verify_exif_data(image_path):
"""
验证图像的EXIF数据是否正确写入
"""
try:
exif_dict = piexif.load(image_path)
print("=== EXIF信息验证 ===")
# 检查基本元数据
if piexif.ImageIFD.Artist in exif_dict["0th"]:
artist = exif_dict["0th"][piexif.ImageIFD.Artist].decode('utf-8')
print(f"作者: {artist}")
if piexif.ImageIFD.Copyright in exif_dict["0th"]:
copyright_info = exif_dict["0th"][piexif.ImageIFD.Copyright].decode('utf-8')
print(f"版权信息: {copyright_info}")
if piexif.ExifIFD.DateTimeOriginal in exif_dict["Exif"]:
create_time = exif_dict["Exif"][piexif.ExifIFD.DateTimeOriginal].decode('utf-8')
print(f"创建时间: {create_time}")
print("✅ EXIF信息验证完成")
return True
except Exception as e:
print(f"❌ EXIF验证失败: {str(e)}")
return False
# 测试函数
def test_watermark_functionality():
"""
完整测试水印和EXIF功能
"""
# 创建一个测试图像
test_image = Image.new('RGB', (1024, 1024), color='red')
test_image.save('test_image.jpg', 'JPEG', quality=95)
# 测试EXIF添加
add_exif_metadata('test_image.jpg', '测试提示词', '测试作者', '© 2024 测试版权')
verify_exif_data('test_image.jpg')
# 测试水印添加
add_text_watermark('test_image.jpg', '测试水印', 'test_watermarked.jpg')
print("✅ 所有测试完成")
7. 总结
通过本教程,你已经学会了如何为WuliArt Qwen-Image Turbo生成的图像添加专业的EXIF元数据和版权水印。这些功能不仅能够保护你的创作成果,还能为图像添加有价值的元信息。
关键要点回顾:
- EXIF信息可以帮助记录图像的创作信息、版权信息和生成参数
- 文字水印适合简单的版权声明,图片水印适合品牌Logo展示
- 通过自动化集成,可以在图像生成后立即进行后处理
- 记得定期验证EXIF信息是否正确写入
实用建议:
- 根据你的需求调整水印的透明度、位置和大小
- 定期备份你的水印配置和EXIF模板
- 考虑创建不同的水印样式用于不同用途的图像
- 测试不同的水印位置,找到最适合你图像风格的方案
现在你可以自信地使用WuliArt Qwen-Image Turbo生成图像,并确保你的创作得到适当的版权保护。这些技能不仅适用于这个特定的AI工具,也可以应用到其他图像生成和处理 workflow中。
获取更多AI镜像
想探索更多AI镜像和应用场景?访问 CSDN星图镜像广场,提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。
更多推荐

所有评论(0)