当前位置: 首页 > ai >正文

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

http://www.xdnf.cn/news/2737.html

相关文章:

  • 防洪评价报告编制方法及洪水建模实践技术-防洪评价报告编制方法及洪水建模实践技术
  • 搭建spark yarn模式集群
  • 为什么使用ThreadLocal后要调用remove()方法呢?
  • 9.5/Q1,GBD数据库最新高分文章解读
  • 机器学习-08-时序数据分析预测
  • 在移动应用开发中,如何优化JavaScript的性能
  • 【行业特化篇2】金融行业简历特化指南:合规性要求与风险控制能力的艺术化呈现
  • 用Python做有趣的AI项目 6:AI音乐生成器(LSTM Melody Generator)
  • 在 cmd shell 中执行 metasploit vbs payload
  • OpenAvatarChat要解决UnicodeDecodeError
  • 一文掌握Matplotlib绘图
  • PyQt6基础_QThread
  • 亚马逊如何分析竞品
  • 网工笔记-网络层
  • 软件工程(一):黑盒测试与白盒测试
  • 【浙江大学DeepSeek公开课】人类经验与AI算法的镜像之旅
  • 考研系列-计算机组成原理第七章、输入/输出系统
  • 解锁健康密码:养生的多维智慧
  • 【手册】Linux服务器应急排查实战指南
  • 《Learning Langchain》阅读笔记11-RAG(7)索引优化:RAPTOR方法和ColBERT方法
  • C++:BST、AVL、红黑树
  • 惠普P1108打印机信息
  • gre over ipsec (神州数码)
  • 巧记英语四级单词 Unit6-中【晓艳老师版】
  • SpringBoot启动后自动执行方法的各种方式-笔记
  • 【MCP】第三篇:Cline工具链路追踪——解码“协议引擎“的神经传导奥秘
  • Pytest-mark使用详解(跳过、标记、参数 化)
  • 夜莺 v8.0.0-beta.10 部署
  • 新能源汽车声纹监测技术的发展趋势是什么?
  • 机器学习:【抛掷硬币的贝叶斯后验概率】