通过Python将读取到的TXT文件内容,根据文件内容自动换算图片分辨率(长*宽)后,生成任意格式图片。(如文件内容过多,导致超出最大图片分辨率时会报错)
导入的包
pip install Pillow
核心方法
1、读取TXT文件内容
def list_dir(path, list_name): # 传入存储的list
for file in os.listdir(path): # os.listdir(path),路径下的文件及文件夹,不包含子文件和子文件夹
file_path = os.path.join(path, file)
if os.path.isdir(file_path): # 判断是否目录
list_dir(file_path, list_name)
else:
list_name.append(file_path)
2、将TXT文件转换为图片文件
class CodeToPicture(object):
def single_len(self, string):
'''获取字符串的单字节长度'''
tab_len = string.count('\t')*4
cn_len = len(re.findall(r'[\u4e00-\u9fa5]',string))*2 # 中文
other_len = len(re.findall(r'[^\t\u4e00-\u9fa5]',string)) # 其他
total_len = tab_len + other_len + cn_len
return total_len
def text_to_image(self,txt_file_path, font_path='msyh.ttc', font_size=50, text_color='black', bg_color='white'):
fontsize = 55 # 字体大小
row_size = 50 # 文字行距
column_size = 15 # 行首缩进
try:
if self.font_file:
font = ImageFont.truetype(font=self.font_file, size=fontsize)
else:
font = ImageFont.truetype(font='simsun.ttc', size=fontsize) # 使用宋体,兼容\t
except Exception as e:
# 系统字体:黑体simhei.ttf、楷体simkai.ttf、雅黑msyh.ttc、仿宋simfang.ttf,均不兼容\t
font = ImageFont.truetype(font='simhei.ttf', size=fontsize) # 系统字体黑体,不兼容\t
# 读取文本文件内容
with open(txt_file_path, 'r', encoding='utf-8') as f:
text = f.read()
#text = text.replace('\\\\r\\\\n', '\\n')
#print(text)
lines = text.split('\n') # 计算行数
row_num = len(lines) # 总共的行数
line_max = max(lines, key=self.single_len) # 单字节最大的行
left, top, right, bottom = font.getbbox( line_max )
# 计算图片高度
image_height = (bottom + row_size) * row_num # 图片高度
image_width = column_size*2 + right #column_size*2 + right # 图片宽度:行首缩进+行尾缩进+tab长度+中文长度
image_size = (image_width, image_height) # 图片尺寸
# 创建一个白色背景的空白图像
img = Image.new('RGB', size=image_size, color=bg_color)
# 在图像上创建一个Draw对象
draw = ImageDraw.Draw(img)
# 设置要绘制的文本和字体
font = ImageFont.truetype(font_path, size=font_size)
# 确定文本的位置,并使用指定的字体和颜色将其绘制到图像上
# text_width, text_height = draw.textsize(text, font=font)
# x = (img.width - text_width) // 2
# y = (img.height - text_height) // 2
# draw.text((x, y), text, fill=text_color, font=font)
for n,line in enumerate(text.split('\n')):
draw.text((column_size, (bottom + row_size)*n), line, font=font, fill=(0,0,0,0))
# 保存图像到文件并返回文件路径
output_file_path = txt_file_path.rsplit('.', 1)[0] + '.png'
img.save(output_file_path)
print(output_file_path+':success')
return output_file_path
3、批量执行
if __name__ == '__main__':
fileList=[]
list_dir(r"D:\iis_logs\logs\LogFiles\W3SVC1", fileList)
ctp=CodeToPicture()
for file in fileList:
if file.split(".")[-1]=="txt":
print(file+":begin")
ctp.text_to_image(file)
转换过程及效果



➡️ 资源下载:
https://download.csdn.net/download/s1t16/88208805
注:如当前文章或代码侵犯了您的权益,请私信作者删除!
文章介绍了一个Python程序,通过读取TXT文件的内容,根据内容自动计算图片的分辨率,并生成相应的图片。使用Pillow库实现,如果文件内容过大导致分辨率超限会报错。程序还提供了批量处理功能,适用于文本日志文件转换。

1152

被折叠的 条评论
为什么被折叠?



