from PIL import Image,文字成图,ImageFontimport jieba分词,input优雅python绘制图片

本文主要是介绍from PIL import Image,文字成图,ImageFontimport jieba分词,input优雅python绘制图片,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

开始的代码

import os
from PIL import Image, ImageDraw, ImageFont
import jiebadef generate_image_with_white_bg(text, font_path, output_path):# 设置图片大小和背景颜色image_width = 800image_height = 600bg_color = (255, 255, 255)  # 白色# 创建图片对象image = Image.new("RGB", (image_width, image_height), bg_color)draw = ImageDraw.Draw(image)# 设置字体和字体大小font_size = 36font = ImageFont.truetype(font_path, font_size)# 将文本按行分割lines = text.split("\n")# 绘制文本y = 50  # 初始纵坐标for line in lines:words = jieba.lcut(line)  # 分词去重for word in words:word = word.replace(",", " ").replace("。", " ").replace("?", " ")  # 替换标点符号为空格draw.text((50, y), word, fill=(0, 0, 0), font=font)  # 绘制文本y += 50  # 纵坐标递增# 保存图片image.save(output_path)def generate_image_with_black_bg(text, font_path, output_path):# 设置图片大小和背景颜色image_width = 800image_height = 600bg_color = (0, 0, 0)  # 黑色# 创建图片对象image = Image.new("RGB", (image_width, image_height), bg_color)draw = ImageDraw.Draw(image)# 设置字体和字体大小font_size = 36font = ImageFont.truetype(font_path, font_size)# 将文本按行分割lines = text.split("\n")# 绘制文本y = 50  # 初始纵坐标for line in lines:words = jieba.lcut(line)  # 分词去重for word in words:word = word.replace(",", " ").replace("。", " ").replace("?", " ")  # 替换标点符号为空格draw.text((50, y), word, fill=(255, 255, 255), font=font)  # 绘制文本y += 50  # 纵坐标递增# 保存图片image.save(output_path)def main():# 输入文本内容print("请输入多行文本内容,以空行结束:")text = ""while True:line = input()if line == "":breaktext += line + "\n"# 创建保存路径save_path = "/storage/emulated/0/文件/aidliux/生成图片/"os.makedirs(save_path, exist_ok=True)# 生成白底黑字宋体图片default_font_path = "path_to_default_font.ttf"  # 将此处替换为安卓默认字体文件路径white_bg_output_path = os.path.join(save_path, "white_bg_simsun.jpg")generate_image_with_white_bg(text, default_font_path, white_bg_output_path)# 生成黑底白字宋体图片black_bg_output_path = os.path.join(save_path, "black_bg_simsun.jpg")generate_image_with_black_bg(text, default_font_path, black_bg_output_path)print("白底黑字宋体图片已生成,保存路径为:{}".format(white_bg_output_path))print("黑底白字宋体图片已生成,保存路径为:{}".format(black_bg_output_path))if __name__ == "__main__":main()

运行的结果

/data/user/0/org.qpython.qpy/files/bin/qpy thon3.sh "/storage/emulated/0/qpython/表格 操作行列1.2.5.6.5.文字成图.py" && exit
作行列1.2.5.6.5.文字成图.py" && exit     < 请输入多行文本内容,以空行结束:
优雅之美Traceback (most recent call last):File "/storage/emulated/0/qpython/表格操 作行列1.2.5.6.5.文字成图.py", line 90, in  <module>main()File "/storage/emulated/0/qpython/表格操 作行列1.2.5.6.5.文字成图.py", line 80, in  maingenerate_image_with_white_bg(text, def ault_font_path, white_bg_output_path)File "/storage/emulated/0/qpython/表格操 作行列1.2.5.6.5.文字成图.py", line 17, in  generate_image_with_white_bgfont = ImageFont.truetype(font_path, f ont_size)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^File "/data/user/0/org.qpython.qpy/files /lib/python3.11/site-packages/PIL/ImageFon t.py", line 976, in truetypereturn freetype(font)^^^^^^^^^^^^^^File "/data/user/0/org.qpython.qpy/files /lib/python3.11/site-packages/PIL/ImageFon t.py", line 973, in freetypereturn FreeTypeFont(font, size, index,  encoding, layout_engine)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^File "/data/user/0/org.qpython.qpy/files /lib/python3.11/site-packages/PIL/ImageFon t.py", line 249, in __init__self.font = core.getfont(^^^^^^^^^^^^^
OSError: cannot open resource
1|:/ $
1|:/ $

错误❌print

这个错误是由于缺少字体文件导致的。在代码中,你需要替换default_font_path变量为安卓设备上的默认字体文件路径。

你可以按照以下步骤来解决这个问题:

1. 在安卓设备上找到默认字体文件路径。通常情况下,它们位于/system/fonts/目录下,文件名可能是DroidSans.ttfNotoSansCJK-Regular.ttc等。你可以使用文件管理器或者终端来查找。

2. 将找到的默认字体文件路径替换到代码中的default_font_path变量。例如,假设找到的路径是/system/fonts/DroidSans.ttf,则代码中应该替换为default_font_path = "/system/fonts/DroidSans.ttf"

完成以上步骤后,再次运行代码,应该就能正常生成图片了。

我们增加了一些改进的

文件名命名方法:编号. 词语 时间戳
保存 /storage/emulated/0/文件/代码print相关/结构图/
没有就新建
中文字体 /storage/emulated/0/文件/字体大全/字体包/宋体.ttf
其它中文字体 /storage/emulated/0/文件/字体大全/字体包/
英语字体 /storage/emulated/0/文件/字体大全/
这个目录下检索可用英语.ttf,如果需要英语的话
文件名没有库或者样式就省略掉

改进的代码

这段代码比较长,你可以按照以下代码来更新你的程序:

import os
import time
from PIL import Image, ImageDraw, ImageFont
import jiebadef generate_image_with_white_bg(text, font_path, output_path):# 设置图片大小和背景颜色image_width = 800image_height = 600bg_color = (255, 255, 255)  # 白色# 创建图片对象image = Image.new("RGB", (image_width, image_height), bg_color)draw = ImageDraw.Draw(image)# 设置字体和字体大小font_size = 36font = ImageFont.truetype(font_path, font_size)# 将文本按行分割lines = text.split("\n")# 绘制文本y = 50  # 初始纵坐标for line in lines:words = jieba.lcut(line)  # 分词去重for word in words:word = word.replace(",", " ").replace("。", " ").replace("?", " ")  # 替换标点符号为空格draw.text((50, y), word, fill=(0, 0, 0), font=font)  # 绘制文本y += 50  # 纵坐标递增# 保存图片image.save(output_path)def generate_image_with_black_bg(text, font_path, output_path):# 设置图片大小和背景颜色image_width = 800image_height = 600bg_color = (0, 0, 0)  # 黑色# 创建图片对象image = Image.new("RGB", (image_width, image_height), bg_color)draw = ImageDraw.Draw(image)# 设置字体和字体大小font_size = 36font = ImageFont.truetype(font_path, font_size)# 将文本按行分割lines = text.split("\n")# 绘制文本y = 50  # 初始纵坐标for line in lines:words = jieba.lcut(line)  # 分词去重for word in words:word = word.replace(",", " ").replace("。", " ").replace("?", " ")  # 替换标点符号为空格draw.text((50, y), word, fill=(255, 255, 255), font=font)  # 绘制文本y += 50  # 纵坐标递增# 保存图片image.save(output_path)def main():# 输入文本内容print("请输入多行文本内容,以空行结束:")text = ""while True:line = input()if line == "":breaktext += line + "\n"# 创建保存路径output_dir = "/storage/emulated/0/文件/代码print相关/结构图/"os.makedirs(output_dir, exist_ok=True)# 初始化时间戳timestamp = int(time.time())# 获取中文字体路径chinese_font_path = "/storage/emulated/0/文件/字体大全/字体包/宋体.ttf"# 获取英文字体路径english_font_path = Noneenglish_fonts_dir = "/storage/emulated/0/文件/字体大全/"for filename in os.listdir(english_fonts_dir):if filename.endswith(".ttf"):english_font_path = os.path.join(english_fonts_dir, filename)break# 生成白底黑字宋体图片white_bg_output_path = os.path.join(output_dir, "{}.{}.jpg".format(len(text), timestamp))generate_image_with_white_bg(text, chinese_font_path, white_bg_output_path)# 生成黑底白字宋体图片black_bg_output_path = os.path.join(output_dir, "{}.{}.jpg".format(len(text), timestamp))generate_image_with_black_bg(text, chinese_font_path, black_bg_output_path)print("白底黑字宋体图片已生成,保存路径为:{}".format(white_bg_output_path))print("黑底白字宋体图片已生成,保存路径为:{}".format(black_bg_output_path))if english_font_path is not None:# 生成白底黑字英语图片white_bg_output_path = os.path.join(output_dir, "{}e.{}.jpg".format(len(text), timestamp))generate_image_with_white_bg(text, english_font_path, white_bg_output_path)# 生成黑底白字英语图片black_bg_output_path = os.path.join(output_dir, "{}e.{}.jpg".format(len(text), timestamp))generate_image_with_black_bg(text, english_font_path, black_bg_output_path)print("白底黑字英语图片已生成,保存路径为:{}".format(white_bg_output_path))print("黑底白字英语图片已生成,保存路径为:{}".format(black_bg_output_path))if __name__ == "__main__":main()

这个程序会根据输入的文本生成4张图片,分别是白底黑字宋体图片、黑底白字宋体图片、白底黑字英语图片和黑底白字英语图片。其中,中文字体使用的是/storage/emulated/0/文件/字体大全/字体包/宋体.ttf,英文字体则是在/storage/emulated/0/文件/字体大全/目录下查找的第一个.ttf文件作为默认字体。保存路径为/storage/emulated/0/文件/代码print相关/结构图/,文件名格式为编号. 词语 时间戳.jpg。如果没有对应的库或者样式,则省略掉,例如只有编号和时间戳的情况。

请注意,英文字体在中文文本中可能会出现乱码,需要根据实际情况进行调整。

结果

在这里插入图片描述
让我们看看有没有这个文件,可以看到只生成的两个图片
在这里插入图片描述
这样对我来说就是基本有一个雏形了
在这里插入图片描述
前面是用中文打的,我的字体夹还真包里有很多字体,目前可能晕倒。
在这里插入图片描述
这是用英文打的,就是2个框框加2个XX,可以看到是俩扑克牌!

这篇关于from PIL import Image,文字成图,ImageFontimport jieba分词,input优雅python绘制图片的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1231

相关文章

Python错误AttributeError: 'NoneType' object has no attribute问题的彻底解决方法

《Python错误AttributeError:NoneTypeobjecthasnoattribute问题的彻底解决方法》在Python项目开发和调试过程中,经常会碰到这样一个异常信息... 目录问题背景与概述错误解读:AttributeError: 'NoneType' object has no at

Python使用openpyxl读取Excel的操作详解

《Python使用openpyxl读取Excel的操作详解》本文介绍了使用Python的openpyxl库进行Excel文件的创建、读写、数据操作、工作簿与工作表管理,包括创建工作簿、加载工作簿、操作... 目录1 概述1.1 图示1.2 安装第三方库2 工作簿 workbook2.1 创建:Workboo

基于Python实现简易视频剪辑工具

《基于Python实现简易视频剪辑工具》这篇文章主要为大家详细介绍了如何用Python打造一个功能完备的简易视频剪辑工具,包括视频文件导入与格式转换,基础剪辑操作,音频处理等功能,感兴趣的小伙伴可以了... 目录一、技术选型与环境搭建二、核心功能模块实现1. 视频基础操作2. 音频处理3. 特效与转场三、高

Python实现中文文本处理与分析程序的示例详解

《Python实现中文文本处理与分析程序的示例详解》在当今信息爆炸的时代,文本数据的处理与分析成为了数据科学领域的重要课题,本文将使用Python开发一款基于Python的中文文本处理与分析程序,希望... 目录一、程序概述二、主要功能解析2.1 文件操作2.2 基础分析2.3 高级分析2.4 可视化2.5

一文解密Python进行监控进程的黑科技

《一文解密Python进行监控进程的黑科技》在计算机系统管理和应用性能优化中,监控进程的CPU、内存和IO使用率是非常重要的任务,下面我们就来讲讲如何Python写一个简单使用的监控进程的工具吧... 目录准备工作监控CPU使用率监控内存使用率监控IO使用率小工具代码整合在计算机系统管理和应用性能优化中,监

Python实现终端清屏的几种方式详解

《Python实现终端清屏的几种方式详解》在使用Python进行终端交互式编程时,我们经常需要清空当前终端屏幕的内容,本文为大家整理了几种常见的实现方法,有需要的小伙伴可以参考下... 目录方法一:使用 `os` 模块调用系统命令方法二:使用 `subprocess` 模块执行命令方法三:打印多个换行符模拟

Python实现MQTT通信的示例代码

《Python实现MQTT通信的示例代码》本文主要介绍了Python实现MQTT通信的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 安装paho-mqtt库‌2. 搭建MQTT代理服务器(Broker)‌‌3. pytho

基于Python开发一个图像水印批量添加工具

《基于Python开发一个图像水印批量添加工具》在当今数字化内容爆炸式增长的时代,图像版权保护已成为创作者和企业的核心需求,本方案将详细介绍一个基于PythonPIL库的工业级图像水印解决方案,有需要... 目录一、系统架构设计1.1 整体处理流程1.2 类结构设计(扩展版本)二、核心算法深入解析2.1 自

从入门到进阶讲解Python自动化Playwright实战指南

《从入门到进阶讲解Python自动化Playwright实战指南》Playwright是针对Python语言的纯自动化工具,它可以通过单个API自动执行Chromium,Firefox和WebKit... 目录Playwright 简介核心优势安装步骤观点与案例结合Playwright 核心功能从零开始学习

Python 字典 (Dictionary)使用详解

《Python字典(Dictionary)使用详解》字典是python中最重要,最常用的数据结构之一,它提供了高效的键值对存储和查找能力,:本文主要介绍Python字典(Dictionary)... 目录字典1.基本特性2.创建字典3.访问元素4.修改字典5.删除元素6.字典遍历7.字典的高级特性默认字典