Typora導出html文件時圖片自動轉(zhuǎn)換成base64

在使用markdown工具typora編寫文檔時,由于里面會插入一些本地的圖片,當我們把文檔導出html時發(fā)給其他人時,由于找不到圖片對應的文件,會導致圖片無法顯示。此文將介紹使用擴展命令的方式在導出html時將圖片轉(zhuǎn)換成base64內(nèi)嵌到html文件中,具體參考如下:

注:參考了文章,由于使用時中文發(fā)生了亂碼,做了一些修改:

  1. 修復中文亂碼;
  2. 導出完成后刪除源文件,并重命名為源文件名稱。

1. 編寫Java代碼生成擴展jar包

需要借助Java代碼進行操作,重新讀取已導出的文件,并轉(zhuǎn)換文件中的圖片為base64。已編寫好的jar包下載地址(如果直接下載可以直接跳到第2章節(jié)):點擊下載TyporaToBase64.jar

  1. 代碼實現(xiàn)
package com.ttxz.imagetobase64;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Main {
    /**
     * @param src img src 內(nèi)容
     * @param end 下次查找字符串起始位置
     * @return java.lang.String
     * @throws
     * @description 遞歸執(zhí)行查找同一行字符串多個 img 標簽
     * @date 2021/10/1 11:07
     * @Author Mr.Fang
     */
    public static String execute(String src, int end) {
        String result = matchImg(src, end);
        if (result.isEmpty()) {
            return src;
        } else {
            String[] split = result.split(",");
            String s1 = fileToBase64(split[0]);
            if (s1.isEmpty()) {
                return src;
            } else {
                String replace = src.replace(split[0], s1);
                return execute(replace, Integer.valueOf(split[1]) + 20);
            }
        }
    }

    /**
     * @param str 原始字符串
     * @return java.lang.String
     * @Description 匹配 img src 內(nèi)容
     * @date 2021/9/30 0030 16:32
     * @auther Mr.Fang
     **/
    public static String matchImg(String str, int start) {
        int img = str.indexOf("<img", start); // 起始位置
        if (img == -1) {
            return "";
        }
        int l = str.indexOf("\"", img) + 1; // src 左側(cè) 雙引號
        int r = str.indexOf("\"", l); // src 右側(cè) 雙引號
        String substring = str.substring(l, r);
        if (substring.startsWith("data")) { // 跳過已經(jīng) base64 編碼的文件 和 http 地址
            return matchImg(str, r);
        }
        return substring + "," + r; // src 地址 返回 src 內(nèi)容以及最后的位置 使用逗號拼接
    }

    /**
     * @param path 文件路徑
     * @return java.lang.String
     * @Description 文件轉(zhuǎn) base64
     * @date 2021/9/30 0030 16:37
     * @auther Mr.Fang
     **/
    public static String fileToBase64(String path) {
        File file = new File(path);
        if (!file.exists()) {
            System.err.printf("File not exist!");
            return "";
        }
        byte bytes[] = null;
        try (FileInputStream fileInputStream = new FileInputStream(path);) {
            bytes = new byte[fileInputStream.available()];
            fileInputStream.read(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Image convert base64 fail!");
        }
        // 文件后綴處理
        String suffix = getSuffix(path);
        return "data:image/" + suffix + ";base64," + Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * @param str
     * @return java.lang.String
     * @throws
     * @description 獲取文件后綴
     * @date 2021/10/1 16:43
     * @Author Mr.Fang
     */
    public static String getSuffix(String str) {
        return str.substring(str.lastIndexOf(".") + 1);
    }

    // 主方法
    public static void main(String[] args) {
        // 獲取文件路徑
        if (args.length == 0) {
            System.out.println("No parameters passed");
            return;
        }
        String arg = args[0];
        // 獲取文件后綴
        String suffix = getSuffix(arg);
        File srcFile = new File(arg);

        File outFile = new File(arg.replace("." + suffix, "").concat("-base64.").concat(suffix));
        try (BufferedReader bfr = new BufferedReader(new InputStreamReader(new FileInputStream(srcFile), StandardCharsets.UTF_8));
             BufferedWriter bfw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),StandardCharsets.UTF_8))
        ) {
            String len = "";
            while ((len = bfr.readLine()) != null) {
                String result = "";
                if (len.indexOf("<img") != -1) {
                    result = execute(len, 0);
                }
                if (result.equals("")) {
                    bfw.write(len);
                } else {
                    bfw.write(result);
                }
            }
            //必須關閉IO流,否則無法操作文件
            bfr.close();
            bfw.close();
            //成功,刪除轉(zhuǎn)換成功的源文件
            boolean resultDelete = srcFile.delete();
            System.out.println("Sorce file delete finish, " + resultDelete);
            boolean reultRename = outFile.renameTo(srcFile);
            System.out.println("Out file rename finish, " + reultRename);
            System.out.println("File convert success!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("error");
            System.out.println("File convert fail!");
        }

    }
}
  1. 打包jar


    1. 進入項目配置

    2. 打開Artifacts選項卡

    3. 點擊新增

    4. 選擇JAR配置

    5. Create JAR from Modules

    6. 選擇模塊

    7. 點擊確定

    8. 點擊確定

    9. 選擇Build Artifacts

    10. 選擇Build

    11. 查看輸出Jar包
  2. Typora配置
  • Typora提供了導出后可以執(zhí)行自定義命令
  • 首先將生成的Jar或是下載的,復制到Typora的安裝目錄下(默認安裝路徑是:C:\Program Files\Typora
  • 打開Typora,依次點擊文件-偏好設置-導出-HTML
  • 勾選運行自定義命令和顯示命令行輸出
  • 在自定義命令處輸入自定義的指令(依賴java環(huán)境):
java -jar C:\Program" "Files\Typora\TyporaToBase64.jar "${outputPath}"
  • 配置完成后如圖示:


    Typora配置自定義命令
  • 最終導出的輸出示例:


    Typora導出成功示例
  • 注:更多參數(shù)信息查看官網(wǎng) https://support.typora.io/Export/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容