笔记迁移到博客的图片问题最终解决方案

lena dahuaidan

哈哈哈
分两种情况:

  1. 在学习仓库里编辑的文章,通过ob的envelope插件传到github,然后pull后执行脚本,脚本实现移动图片加修改.md中图片内链
    • 在学习仓库里还是![[]]格式,且选择内部链接类型为“尽可能简短模式”,这个要关掉
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
	import os

import shutil

import re

import urllib.parse



def move_images_and_update_links(posts_dir, images_dir):

# 遍历_posts文件夹中的所有.md文件

for root, dirs, files in os.walk(posts_dir):

for file in files:

if file.endswith('.md'):

md_file_path = os.path.join(root, file)

print(f"正在处理文件: {md_file_path}")

# 检查文件权限,确保它可写

if not os.access(md_file_path, os.W_OK):

print(f"没有写权限: {md_file_path}")

continue

# 打开.md文件并读取内容

with open(md_file_path, 'r', encoding='utf-8') as f:

content = f.read()



# 查找.md文件中所有的图片链接,处理 ![[...|...]] 格式

new_content = content

image_links = re.findall(r'!\[\[(.*?)\|.*?\]\]', content)



if not image_links:

print(f"未找到图片链接: {md_file_path}")

for image_link in image_links:

# 规范化路径,去掉 './' 部分

image_link = os.path.normpath(image_link) # 去掉 './' 等无效部分

image_name = os.path.basename(image_link)



# 计算图片的源路径

source_image_path = os.path.join(root, image_name)



# 如果图片链接是相对路径,尝试拼接完整路径

if not os.path.exists(source_image_path):

# 如果图片在子目录中,尝试调整路径

source_image_path = os.path.join(posts_dir, image_link)

destination_image_path = os.path.join(images_dir, image_name)



print(f"检查图片路径: {source_image_path}")

# 检查图片是否存在

if os.path.exists(source_image_path):

print(f"正在移动图片: {image_name}")

shutil.move(source_image_path, destination_image_path)



# 在.md文件中将空格替换为 %20

new_link = f'![](../images/{urllib.parse.quote(image_name)})'

# 只替换当前处理的图片链接

new_content = re.sub(r'!\[\[' + re.escape(image_link) + r'\|.*?\]\]', new_link, new_content)

else:

print(f"图片不存在: {source_image_path}")



# 检查文件内容是否实际变化

if new_content != content:

print(f"文件内容已更改,保存修改: {md_file_path}")

with open(md_file_path, 'w', encoding='utf-8') as f:

f.write(new_content)

else:

print(f"文件内容未变化: {md_file_path}")



# 设置_posts和images文件夹路径

posts_dir = './myblog/source/_posts' # 请替换为你实际的路径

images_dir = './myblog/source/images' # 请替换为你实际的路径



move_images_and_update_links(posts_dir, images_dir)
  1. 在博客仓库里编辑的文章,进行以下设置
  • 标题: 笔记迁移到博客的图片问题最终解决方案
  • 作者: lena
  • 创建于: 2025-03-08 20:18:37
  • 更新于: 2025-03-08 21:08:37
  • 链接: https://lenaaa0.github.io/2025/03/dfeeaecfbe86.html
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
 评论
此页目录
笔记迁移到博客的图片问题最终解决方案