前言说明
- 把图片转换为 Base64 代码,可以解决 Markdown 难以内嵌图片的痛点
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| # 插入本地图片(不好分享,本地图片路径更改和丢失,都会导致图片无法加载) 
# 插入网络图片(需将图片先上传至网络) 
# 插入图片的Base64码 
# Base64字符串过于长, 可在末尾设置一个id来调用 ![text][id_0] ...... [id_0]:data:image/x-icon;base64,iVBORwo...
|
但经过 Base64 编码后的图片体积一般比源文件大30%左右,且加载时显示很缓慢
那么如何在网络中使用 Base64 编码后的图片呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| data:[<mime type>][;base64],<data>
background-image: url("data:image/bmp;base64,iVBORwo...");
<img src="data:image/png;base64,iVBORwo..." />

![image][image_id] ......可以把下面这段图片代码放在最后...... [image_id]:data:image/gif;base64,iVBORwo...
|
转换方式
一些在线网站即可 将Picture转Base64
Python代码Base64转换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| file = open('/home/picture/0.png', 'rb') base_file = base64.b64encode(file.read()) file.close() txt = open('/home/picture/0.txt', 'wb') txt.write(str(base_file)) txt.clost()
base_file = 'fasDWkkS.....' imgData = base64.b64decode(base_file) file = open('/home/picture/1.png', 'wb') file.write(imgData) file.close()
|
- 在PowerShell中转换图片为Base64码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| param( [string]$imagePath )
$imageBytes = [System.IO.File]::ReadAllBytes($imagePath) $base64String = [Convert]::ToBase64String($imageBytes)
$imageTag = "data:image/jpg;base64,$base64String"
Set-Clipboard -Value $imageTag
|
成果展示

这样就可以方便的将图片嵌入Markdown文档中了