#!/usr/bin/env python3
"""
生成带字幕的封面图片
"""
from PIL import Image, ImageDraw, ImageFont
import os

# 创建黑色背景图片 (720x1280)
width, height = 720, 1280
img = Image.new('RGB', (width, height), color='black')
draw = ImageDraw.Draw(img)

# 尝试使用系统中文字体
font_paths = [
    "C:/Windows/Fonts/msyh.ttc",      # 微软雅黑
    "C:/Windows/Fonts/simhei.ttf",    # 黑体
    "C:/Windows/Fonts/simsun.ttc",    # 宋体
]

title_font = None
subtitle_font = None
cn_font = None
en_font = None

for font_path in font_paths:
    if os.path.exists(font_path):
        try:
            title_font = ImageFont.truetype(font_path, 36)
            subtitle_font = ImageFont.truetype(font_path, 24)
            cn_font = ImageFont.truetype(font_path, 32)
            en_font = ImageFont.truetype(font_path, 24)
            print(f"使用字体: {font_path}")
            break
        except:
            continue

if title_font is None:
    print("未找到中文字体，使用默认字体")
    title_font = ImageFont.load_default()
    subtitle_font = ImageFont.load_default()
    cn_font = ImageFont.load_default()
    en_font = ImageFont.load_default()

# 文字内容
title = "师徒一场_张雪峰走好_上"
subtitle = "源自：@梁老师的故事汇"
cn_text = "今年三月中旬，"
en_text = "In mid-March of this year,"

# 计算文字位置（居中）
title_bbox = draw.textbbox((0, 0), title, font=title_font)
title_width = title_bbox[2] - title_bbox[0]
title_x = (width - title_width) // 2
title_y = 150

subtitle_bbox = draw.textbbox((0, 0), subtitle, font=subtitle_font)
subtitle_width = subtitle_bbox[2] - subtitle_bbox[0]
subtitle_x = (width - subtitle_width) // 2
subtitle_y = 220

# 中文字幕位置
cn_bbox = draw.textbbox((0, 0), cn_text, font=cn_font)
cn_width = cn_bbox[2] - cn_bbox[0]
cn_x = (width - cn_width) // 2
cn_y = height // 2 - 40

# 英文字幕位置
en_bbox = draw.textbbox((0, 0), en_text, font=en_font)
en_width = en_bbox[2] - en_bbox[0]
en_x = (width - en_width) // 2
en_y = height // 2 + 40

# 绘制文字
draw.text((title_x, title_y), title, font=title_font, fill='white')
draw.text((subtitle_x, subtitle_y), subtitle, font=subtitle_font, fill='gray')
draw.text((cn_x, cn_y), cn_text, font=cn_font, fill='yellow')
draw.text((en_x, en_y), en_text, font=en_font, fill='white')

# 保存图片
output_path = "shitu_cover_with_subtitle.jpg"
img.save(output_path, quality=95)
print(f"图片已保存: {output_path}")
print(f"图片大小: {os.path.getsize(output_path)} 字节")
