基于Python实现TXT文件自适应转换图片【400010001】

文章介绍了一个Python程序,通过读取TXT文件的内容,根据内容自动计算图片的分辨率,并生成相应的图片。使用Pillow库实现,如果文件内容过大导致分辨率超限会报错。程序还提供了批量处理功能,适用于文本日志文件转换。
Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

通过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
注:如当前文章或代码侵犯了您的权益,请私信作者删除!

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神仙别闹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值