批量转换本地链接为图床链接的脚本
我平时比较喜欢使用wolai、语雀这样的在线markdown工具,但是它们导出markdown时都会使用本地链接图片的方式,这对于上传博客很不方便,于是写了两个脚本分别适用于批量上传md文件的图片至图床并修改为图床链接。
适用于gitee图床的版本
import os
import base64
import requests
# Gitee用户名和仓库名
username = '这里写你的gitee用户名'
repository = '这里写你的仓库名称'
# Gitee个人访问令牌(需要有上传文件到仓库的权限)
token = '这里写你的Gitee个人访问令牌'
# Gitee API请求头
headers = {
'Authorization': f'token {token}'
}
# 上传图片到Gitee图床
def upload_image_to_gitee(image_path):
# 获取文件路径在pictures文件夹中的相对路径
relative_path = image_path.replace(os.getcwd(), '').replace('\\', '/')
if 'pictures' not in relative_path:
relative_path = 'pictures/' + relative_path.split('/')[-1]
# 构建上传文件的URL
upload_url = f"https://gitee.com/api/v5/repos/{username}/{repository}/contents/{relative_path}"
# 读取图片文件内容,并对其进行base64编码
with open(image_path, 'rb') as file:
image_content = base64.b64encode(file.read()).decode('utf-8')
# 构建请求体
data = {
'access_token': token,
'content': image_content,
'message': 'Upload image',
'branch': 'master' # Gitee默认分支名为master,除非已更改
}
# 发起上传文件的请求
response = requests.post(upload_url, data=data)
if response.status_code != 201:
print("图片上传失败,状态码:", response.status_code)
print("错误详情:", response.text) # 打印出错误响应的具体信息
return None
# 解析响应,获取上传后的图片链接
if response.status_code == 201:
return response.json()['content']['download_url']
else:
print("图片上传失败,状态码:", response.status_code)
return None
# 替换Markdown文件中的图片链接为图床链接
def replace_image_links_in_markdown(md_file_path, image_links):
with open(md_file_path, 'r', encoding='utf-8') as file:
content = file.read()
for local_image_path, gitee_image_url in image_links.items():
content = content.replace(local_image_path, gitee_image_url)
with open(md_file_path, 'w', encoding='utf-8') as file:
file.write(content)
# 遍历Markdown文件中的图片链接,上传图片到Gitee图床并更新链接
def upload_images_and_update_links(md_file_path):
base_path = os.path.dirname(md_file_path)
image_folder = os.path.join(base_path, 'image')
image_links = {}
with open(md_file_path, 'r', encoding='utf-8') as file:
lines = file.readlines()
for line in lines:
if line.strip().startswith('!['):
relative_image_path = line.split('(')[1].split(')')[0]
full_image_path = os.path.join(image_folder, relative_image_path.split('/')[-1])
image_links[relative_image_path] = full_image_path
updated_links = {}
for local_image_path, full_image_path in image_links.items():
gitee_image_url = upload_image_to_gitee(full_image_path)
if gitee_image_url:
updated_links[local_image_path] = gitee_image_url
replace_image_links_in_markdown(md_file_path, updated_links)
# 示例使用
md_file_path = r'这里写你要转换的文件的路径'
upload_images_and_update_links(md_file_path)
使用方法:
适用于github图床的版本
import os
import base64
import requests
# GitHub用户名和仓库名
username = '这里写你的github用户名'
repository = '这里写你的仓库名称'
# GitHub个人访问令牌(需要有上传文件到仓库的权限)
token = '这里写你的Github个人访问令牌'
# GitHub API请求头
headers = {
'Authorization': 'token {}'.format(token),
'Accept': 'application/vnd.github.v3+json'
}
# 上传图片到GitHub图床
def upload_image_to_github(image_path):
# 构建上传文件的URL
upload_url = "https://api.github.com/repos/{}/{}/contents/{}".format(username, repository, image_path.replace(os.getcwd(), '').replace('\\', '/'))
# 读取图片文件内容,并对其进行base64编码
with open(image_path, 'rb') as file:
image_content = base64.b64encode(file.read()).decode('utf-8')
# 构建请求体
data = {
'message': 'Upload image',
'content': image_content,
'branch': 'main' # 或其他分支名
}
# 发起上传文件的请求
response = requests.put(upload_url, headers=headers, json=data)
# 解析响应,获取上传后的图片链接
if response.status_code == 201:
return response.json()['content']['download_url']
else:
print("图片上传失败,状态码:", response.status_code)
return None
# 替换Markdown文件中的图片链接为图床链接
def replace_image_links_in_markdown(md_file_path, image_links):
with open(md_file_path, 'r', encoding='utf-8') as file:
content = file.read()
for local_image_path, github_image_url in image_links.items():
content = content.replace(local_image_path, github_image_url)
with open(md_file_path, 'w', encoding='utf-8') as file:
file.write(content)
# 遍历Markdown文件中的图片链接,上传图片到GitHub图床并更新链接
def upload_images_and_update_links(md_file_path):
base_path = os.path.dirname(md_file_path)
image_folder = os.path.join(base_path, 'image')
image_links = {}
with open(md_file_path, 'r', encoding='utf-8') as file:
lines = file.readlines()
for line in lines:
if line.strip().startswith('!['):
relative_image_path = line.split('(')[1].split(')')[0]
full_image_path = os.path.join(image_folder, relative_image_path.split('/')[-1])
image_links[relative_image_path] = full_image_path
updated_links = {}
for local_image_path, full_image_path in image_links.items():
github_image_url = upload_image_to_github(full_image_path)
if github_image_url:
updated_links[local_image_path] = github_image_url
replace_image_links_in_markdown(md_file_path, updated_links)
# 示例使用
md_file_path = r'这里写你要转换的文件的路径'
upload_images_and_update_links(md_file_path)
使用方法
注意⚠️
运行时要关闭代理网络!