Markdown图片压缩到文件中

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#coding=utf-8
import base64
import time
import os
import re


name = 'hhh'
filename = name + ".md"
temfile = name + 'base64' + ".md"

def create_file(path):
picdir = path +'assets\\'
ls = os.listdir(picdir)
targetfile = path + temfile
print(targetfile)
for i in ls :
mulu=str(picdir)+str(i)
f=open(mulu,"rb") #以二进制形式打开str(ls_f)[2:-1]
ls_f = base64.b64encode(f.read())
link = 'assets/'+i
link_str = '\r\n' + f"[{link}]:data:image/png;base64," + str(ls_f)[2:-1]
#print(link_str)
with open(targetfile, 'a+', encoding='utf-8') as file:
file.write(link_str)

def change(path):
tar = path + filename
tars = path + temfile

picdir = path +'assets\\'
ls = os.listdir(picdir)

with open(tar, 'r+', encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
for i in ls:
if i in line:
line = f"![{i[0:-4]}][assets/{i}]"+ '\n'
with open(tars, 'a+', encoding='utf-8') as file:
file.write(line)

if __name__ == '__main__':
start=time.time()
path=os.getcwd()+'\\'
ls = os.listdir(path)
for i in ls:
res = re.findall(r'(.*?).md',i)
if len(res):
name = res[0]
filename = name + ".md"
temfile = name + 'base64' + ".md"
break
for i in ls:
res = re.findall(r'(.*?)base64.md',i)
if len(res):
rmfile = path + temfile
os.remove(rmfile)
print(filename)
change(path)
create_file(path)
print('post time:',time.time()-start)