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
|
import os import re from PIL import Image
def change_to_webp(): """ 将 source\_posts目录下的所有图片格式(webp/webp)转换成webp。 并将对应的md文件中插入图片的语句相应的更改成webp.如:<img src="./1.webp" /> ==>>> <img src="./1.webp" /> """ fold = r"/run/media/xiaoyx/Data/BLOG/yxhsiao/source/_posts" imgs = [ os.path.join(p, j) for p, d, f in os.walk(fold) for j in f if re.search('\.webp$|\.webp$', j) ] for img in imgs: im = Image.open(img).convert('RGB') im.save(re.sub('webp|webp', 'webp', img)) os.remove(img)
files = [ os.path.join(fold, i) for i in os.listdir(fold) if re.search('\.md$', i) ] for file in files: with open(file, 'r', encoding='utf-8') as f, open(f'{file}.bak', 'w', encoding='utf-8') as newfile: for line in f.readlines(): newfile.write(re.sub('webp|webp', 'webp', line)) os.remove(file) os.rename(f'{file}.bak', file)
if __name__ == "__main__": change_to_webp()
|