Python用来写各种小工具简直是神器,昨天晚上花了点时间实现了一个图片转像素风的小工具,下面附上图片Demo和代码

下面是实现的具体代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from PIL import Image  
import argparse

# 命令行输入参数处理
parser = argparse.ArgumentParser()

parser.add_argument('file') # 输入文件
parser.add_argument('-o', '--output') # 输出文件
parser.add_argument('--maxlen', type=int, default=150)

# 获取参数
args = parser.parse_args()

IMG = args.file
MAXLEN = args.maxlen
OUTPUT = args.output

def resize_image(im):
(width, height) = im.size
max_len = max(width, height)

if max_len <= MAXLEN:
return im
else:
scale = max_len / MAXLEN
size = (int(width//scale), int(height//scale))
return im.resize(size, Image.NEAREST)

if __name__ == '__main__':

im = Image.open(IMG)
im = resize_image(im)

txt = ""
(width, height) = im.size
for i in range(height):
for j in range(width):
(r, b, g) = im.getpixel((j, i))
txt += "<font style='background:rgb({},{},{});display:inline-block;width:3px;height:3px;margin:1px;'></font>".format(r, b, g)
txt += '</br>'

if not OUTPUT:
OUTPUT = "output.txt"

with open(OUTPUT,'w') as f:
f.write(txt)