Hugo:图片存储路径优化

Posted by Nefelibata on Thu 2024-03-21 | | about 1 mins
Last Modified on Thu 2024-05-23

使用hugo搭建博客的时候,md文件的图片存储路径有问题,对其进行改进

1、typora配置

图像存储路径改为如图,其中是以相对路径 ./ 开头

image-20240321185821924

2、用py自动化流程

hugo-root 路径下,新建 img_move.py 文件,并将其放进 Hugo日常更新流程

py代码如下:

 1import os
 2import shutil
 3import codecs
 4
 5# 定义源路径和目标路径
 6source_path = "content/post/postimg"
 7destination_path = "static/img"
 8
 9# 复制文件,如果目标路径已存在文件则不覆盖
10for filename in os.listdir(source_path):
11    source_file = os.path.join(source_path, filename)
12    destination_file = os.path.join(destination_path, filename)
13    if not os.path.exists(destination_file):
14        shutil.copy2(source_file, destination_file)
15        print(f"文件 {source_file} 复制成功!")
16    else:
17        print(f"pass")
18print(f"----------------------------------")
19# 遍历md文件并替换字符串
20md_files = [f for f in os.listdir("content/post") if f.endswith(".md")]
21for md_file in md_files:
22    md_file_path = os.path.join("content/post", md_file)
23    with codecs.open(md_file_path, 'r', encoding='utf-8', errors='ignore') as file:
24        content = file.read()
25    new_content = content.replace('/img/', '/img/')
26    if content != new_content:
27        with codecs.open(md_file_path, 'w', encoding='utf-8', errors='ignore') as file:
28            file.write(new_content)
29        print(f"文件 {md_file_path} 替换成功!")
30    else:
31        print(f"pass")