python裁剪小说封面标题
一张矩形图片 比如50*100 大小
中心点的坐标是是(0,0)
左上角是(-25,50)
右上角是(25,50)
左下角是(-25,-50)
右下角是(25,-50)
我希望你能用python,帮我对本地指定图片切割大小,计算出该图片的中心坐标,然后按照我输入的长宽具体值,比如830*1175,裁剪图片,保存新文件
1.我希望输入指定的宽高,比如830*1175
2.保持原有的裁剪逻辑不变,按照矩形图片的中心点(0,0)为坐标,计算并裁剪图片,保持文件
效果图:
step0:去一些资源网下载超高清大图
step1:裁剪成飞卢的样式 830*1175
from PIL import Imagedef crop_image_center(img_path, target_width, target_height, save_path):"""从图片中心裁剪指定尺寸:param img_path: 原始图片路径:param target_width: 目标宽度:param target_height: 目标高度:param save_path: 保存路径"""try:img = Image.open(img_path)original_width, original_height = img.size# 计算裁剪区域坐标(PIL坐标系)left = (original_width - target_width) // 2top = (original_height - target_height) // 2right = left + target_widthbottom = top + target_height# 验证裁剪尺寸if target_width > original_width or target_height > original_height:raise ValueError(f"原图尺寸({original_width}x{original_height})小于目标尺寸({target_width}x{target_height})")# 执行裁剪并保存cropped_img = img.crop((left, top, right, bottom))cropped_img.save(save_path)print(f"图片已保存至:{save_path}")except Exception as e:print(f"处理失败:{str(e)}")# 使用示例
img_path = r"C:\Users\wangrusheng\Downloads\dce\age.jpg"
save_path = r"C:\Users\wangrusheng\Downloads\dce\age_cropped3.jpg"# 输入你的目标尺寸(示例:830*1175)
target_width = 830
target_height = 1175crop_image_center(img_path, target_width, target_height, save_path)
step2:添加小说标题 生成新图片
C:\Users\wangrusheng\PycharmProjects\FastAPIProject1\hello.py
C:\Users\wangrusheng\PycharmProjects\FastAPIProject1\novel_cover.jpg
from PIL import Image, ImageDraw, ImageFont
import osdef create_novel_cover(img_path, title, font_path=None, color='white', output_path='output.jpg', max_line_length=8):"""创建小说封面参数:img_path: 背景图片路径title: 小说标题font_path: 中文字体路径(默认使用Windows系统字体)color: 文字颜色output_path: 输出文件路径max_line_length: 单行最大字数"""# 打开背景图片bg_image = Image.open(img_path)bg_width, bg_height = bg_image.sizedraw = ImageDraw.Draw(bg_image)# 自动分割标题def split_title(title):if len(title) <= max_line_length:return [title]split_pos = len(title) // 2return [title[:split_pos], title[split_pos:]]lines = split_title(title)# 设置字体路径(Windows系统默认字体)if font_path is None:if os.name == 'nt':font_path = 'C:/Windows/Fonts/simhei.ttf'if not os.path.exists(font_path):raise FileNotFoundError("未找到默认字体,请手动指定中文字体路径")# 动态调整字体大小max_font_size = bg_height // 6min_font_size = 20optimal_size = max_font_size# 通过二分查找找到合适字体大小left, right = min_font_size, max_font_sizewhile left <= right:mid = (left + right) // 2font = ImageFont.truetype(font_path, mid)max_width = max(draw.textbbox((0, 0), line, font=font)[2] for line in lines)if max_width < bg_width * 0.8:optimal_size = midleft = mid + 1else:right = mid - 1font = ImageFont.truetype(font_path, optimal_size)# 计算文字位置text_heights = [draw.textbbox((0, 0), line, font=font)[3] for line in lines]total_height = sum(text_heights) + 10 * (len(lines)-1) # 行间距10px# 垂直位置(位于图片上半部分)y = (bg_height // 9) - (total_height // 5)y = max(y, 20) # 保持最小上边距# 绘制文字for i, line in enumerate(lines):text_width = draw.textbbox((0, 0), line, font=font)[2]x = (bg_width - text_width) // 2draw.text((x, y), line, fill=color, font=font)y += text_heights[i] + 10# 保存结果bg_image.save(output_path)return output_path# 使用示例
if __name__ == "__main__":img_path = r"C:\Users\wangrusheng\Downloads\dce\name.jpg"output_path = create_novel_cover(img_path=img_path,title="重生之商海浮沉",color="#FFFF00", # 白色文字output_path="novel_cover.jpg")print(f"封面已生成:{output_path}")
end