可将markdown格式的图片转为 html格式的图片,即可正常显示
python 代码:
import re
import os
# 读取本目录(及所有子目录)下的.md结尾的文件,将文件中所有图片格式进行转换
def convert_md_to_html(content):
"""
将markdown格式的图片链接转换为HTML的<img>标签。
"""
md_image_pattern = re.compile(r'!\[([^\]]*)\]\(([^)]+)\)')
html_image= md_image_pattern.subn(r'<img alt="\1" src="\2" />', content)
return html_image
def process_md_files(directory):
"""
遍历指定目录,处理所有markdown文件
"""
for root, _, files in os.walk(directory):
for file in files:
if file.endswith('.md'):
file_path = os.path.join(root,file)
with open(file_path, 'r', encoding='utf-8') as fb:
old_content = fb.read()
new_content = convert_md_to_html(old_content)
with open(file, 'w', encoding='utf-8') as fb:
fb.write(new_content[0])
print(f"文件: {file_path}, 成功转换{new_content[1]}张照片")
script_dir = os.path.dirname(os.path.abspath(__file__))
process_md_files(script_dir)
还写了一个用python的图形库tkinter实现的UI界面
import os
import re
from tkinter import *
from tkinter import ttk,filedialog,messagebox
def convert_md_to_html_img(content):
"""
将markdown格式的图片链接转换为HTML的<img>标签。
"""
md_image_pattern = re.compile(r'!\[([^\]]*)\]\(([^)]+)\)')
html_content = md_image_pattern.subn(r'<img alt="\1" src="\2" />', content)
return html_content
def process_md_file(file_path):
"""
处理一个Markdown文件,将Markdown图片链接转换为HTML格式。
"""
try:
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
new_content = convert_md_to_html_img(content)
with open(file_path, 'w', encoding='utf-8') as file:
file.write(new_content[0])
messagebox.showinfo("Success", f"文件: {file_path}, 成功转换{new_content[1]}张照片")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
def select_file():
"""
打开文件选择对话框,让用户选择一个Markdown文件。
"""
file_path = filedialog.askopenfilename(
filetypes=[("Markdown files", "*.md"), ("All files", "*.*")]
)
if file_path:
process_md_file(file_path)
def init():
# 创建主窗口
root = Tk()
root.title("Markdown to HTML Image Converter")
window_width = 200
window_height = 100
root.geometry(f"{window_width}x{window_height}")
# 获取屏幕尺寸
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
# 计算窗口在屏幕中心的坐标
center_x = int(screen_width / 2 - window_width / 2)
center_y = int(screen_height / 2 - window_height / 2)
# 设置窗口的位置
root.geometry(f"+{center_x}+{center_y}")
frame = ttk.Frame(root, padding="3 3 12 12")
frame.grid()
ttk.Button(frame, text="Choose Markdown File",command=select_file).grid(row=50,column=50)
# 运行主窗口
root.mainloop()
init()