Python 文本文件拖上转自适应图片 - 学习笔记(2022.11.16)

Python 文本文件拖上转自适应图片

功能:

  1、支持拖拽执行

  2、文本文件转为自适应尺寸图片

 1 import re
 2 import os
 3 import sys
 4 import time
 5 from PIL import Image,ImageFont,ImageDraw
 6 
 7 class CodeToPicture(object):
 8     """  源码转图片
 9     # 1、支持拖上执行
10     # 2、读取源码内容 , 兼容中文
11     # 3、保存为尺寸大小最为合适图片
12     """
13     run_path = None
14     font_color = (0,0,0,255)
15     def __init__(self):
16         self.font_file = 'c:\\windows\\Fonts\\simsun.ttc' # 宋体
17 
18     def single_len(self, string):
19         '''获取字符串的单字节长度'''
20         tab_len = string.count('\t')*4
21         cn_len = len(re.findall(r'[\u4e00-\u9fa5]',string))*2       # 中文
22         other_len = len(re.findall(r'[^\t\u4e00-\u9fa5]',string))   # 其他
23         total_len = tab_len + other_len + cn_len
24         return total_len
25 
26     # 读取文件内容
27     def read_content(self):
28         try:
29             with open(self.run_path,'r',encoding='utf-8') as f:
30                 return f.read()
31         except Exception as e:
32             print(e)
33 
34     # 保存为图片
35     def save_image(self, text):
36         fontsize = 20      # 字体大小
37         image_width = 1920 # 图片宽度
38         image_height = 0   # 图片高度
39         row_size = 5       # 文字行距
40         column_size = 5    # 行首缩进
41         image_name = os.path.splitext(os.path.basename(self.run_path))[0] # 获取文件名,不包含文件后缀
42         try:
43             if self.font_file:
44                 font = ImageFont.truetype(font=self.font_file, size=fontsize)
45             else:
46                 font = ImageFont.truetype(font='simsun.ttc', size=fontsize) # 使用宋体,兼容\t
47         except Exception as e:
48             # 系统字体:黑体simhei.ttf、楷体simkai.ttf、雅黑msyh.ttc、仿宋simfang.ttf,均不兼容\t
49             font = ImageFont.truetype(font='simhei.ttf', size=fontsize) # 系统字体黑体,不兼容\t
50         lines = text.split('\n')                          # 计算行数
51         row_num = len(lines)                              # 总共的行数
52         line_max = max(lines, key=self.single_len)        # 单字节最大的行
53         left, top, right, bottom = font.getbbox( line_max )
54 
55         # 计算图片高度
56         image_height = (bottom + row_size) * row_num  # 图片高度
57         image_width = column_size*2 + right           # 图片宽度:行首缩进+行尾缩进+tab长度+中文长度
58         image_size = (image_width, image_height)      # 图片尺寸
59 
60         im = Image.new( mode='RGBA',size=image_size, color=self.font_color) # (宽度1920,高度1080)
61         draw = ImageDraw.Draw(im)
62         for n,line in enumerate(text.split('\n')):
63             draw.text((column_size, (bottom + row_size)*n), line, font=font, fill=(0,0,0,0))
64         im.save( "{}_{}_{}.png".format(
65                     image_name,
66                     "%d&%d"%(image_width,image_height),
67                     time.strftime( '%Y-%m-%d_%H-%M-%S', time.localtime() )
68                     ) )
69 
70     def run(self):
71         data = self.read_content()
72         self.save_image(data)
73         print('图片保存成功!')
74         
75 if __name__ == '__main__':
76     try:
77         if sys.argv[1]:
78             ctp = CodeToPicture()
79             ctp.run_path = sys.argv[1]
80             ctp.run()
81     except Exception as e:
82         print(e)
83         time.sleep(10)

实现效果:

 

posted @ 2022-11-16 00:31  猎奇会员  阅读(155)  评论(0)    收藏  举报