在markdown中插入圖片

Markdown是一種可以使用普通文本編輯器編寫的標記語言,通過簡單的標記語法,它可以使普通文本內容具有一定的格式。

1. 在Markdown中插入圖片

由於Markdown是普通文本,所以它無法像word一樣直接在文件中插入圖片。要在Markdown中插入圖片,通常有三種方式。

(1) 插入本地圖片

在Markdown中插入本地圖片的語法爲:

![img](/home/picture/1.png)

括號中爲圖片的路徑,可以是相對路徑或絕對路徑。這種情況下,一旦本地圖片丟失或路徑更改,都無法顯示圖片

(2) 插入網絡圖片

直接在括號裏面填寫網絡圖片路徑即可:

![img](http://baidu.com/picture/picture.png)

這種情況下非常依賴於網絡。

(3) 把圖片存入Markdown文件中

Base64是網絡上最常見的用於傳輸8Bit字節碼的編碼方式之一,Base64就是一種基於64個可打印字符來表示二進制數據的方法。

可以將圖片轉化爲base64編碼,直接放到Markdown文件中,將圖片顯示出來。其語法爲:

![img][figure]

[figure]:data:image/png;base64,iVBORw0...

其中iVBORw0之後爲png格式圖片的base64編碼。可以將其放置於文件的最後。這種情況,如果圖片較多,會導致文件比較大。

本文考慮將圖片轉化爲base64編碼,在Markdown中插入圖片。

2. 算法概述

一般插入的圖片有兩種,一種是直接從剪切板中插入圖片,另一種是從本地文件中導入圖片。

優先考慮剪切板,如果剪切板中有圖片,則將剪切板中的圖片轉化爲base64編碼。如果沒有圖片,則選擇一張本地圖片,獲取其base64編碼。這兩種方式都需要將圖片另存爲png格式,然後獲取這個png格式圖片的base64編碼。

在得到的base64字符串中添加用於Markdown的頭部字符串,並將其寫入剪切板。隨後直接去Markdown文件中粘貼。

3. 程序代碼

使用python 3實現,代碼如下:

# python 3
# writen by Liangjin Song on 20200410
# Convert pictures to base64 encoding for using in markdown
import win32ui,os,base64
from PIL import Image, ImageGrab
import win32clipboard as cb
import win32con

# the temporary picture name
tmp="C:\\Users\\Liangjin\\Pictures\\base6.png"

# saving the picture as the temporary image
def tmp_image():
    # check for pictures in the clipboard
    im = ImageGrab.grabclipboard()
    if isinstance(im, Image.Image):
        # save the picture from the clipbord
        im.save(tmp, "png")
    else:
        # select an image for the disk
        print("No image in clipboard, and please select an image.")
        dlg = win32ui.CreateFileDialog(1)
        dlg.SetOFNInitialDir('C:\\Users\\Liangjin\\Pictures')
        dlg.DoModal()
        filename = dlg.GetPathName()
        im=Image.open(filename)
        # saving the selected picture as a temporary image
        im.save(tmp,'png')

# get the base64 encoding of the temporary image
def img_base64():
    f=open(tmp,'rb')
    # base64 encode
    s=base64.b64encode(f.read())
    # the format used in markdown file
    s=b'[]:data:image/png;base64,'+s
    f.close()
    # delete the temporary image
    os.remove(tmp)
    return s

# Copy base64 encoding to clipboard
def set_clip(s):
    cb.OpenClipboard()
    cb.EmptyClipboard()
    cb.SetClipboardData(win32con.CF_TEXT, s)
    cb.CloseClipboard()

# the main function
if __name__ == '__main__':
    tmp_image()
    set_clip(img_base64())

4. 效果

在這裏插入圖片描述


在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章