markdown的本地图片转BASE64,一起附在文件中

用markdown的时候,插入图片一般有三种方式:

1,用本地图片;

2,用网络图片;

3,把图片编码成BASE64格式,写在文件里面。

本文解决的问题是,把本来引用的本地图片,压缩并编码成BASE64格式放在md文件里面。

import net.coobird.thumbnailator.Thumbnails;
import sun.misc.BASE64Encoder;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Image2Base64 {
    public static final int SCALE = 1;
    public static final float QUALITY = 0.7f;
    public static Pattern compile = Pattern.compile("(!\\[.*\\])\\((.*)\\)");

    public static void main(String[] args) throws Exception {
        // 第一个入参为md的文件。
        if (args[0] == null) {
            System.out.println("wrong file");
            return;
        }
        byte[] buffer = new byte[1024 * 1024];
        String filePath = args[0];
        String fileStr;
        File markdownFile = new File(filePath);
        StringBuilder markdownFileStr = new StringBuilder();
        
        // 读入md文件并用正则进行搜索
        try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(markdownFile));
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            while (bufferedInputStream.read(buffer) != -1) {
                byteArrayOutputStream.write(buffer);
            }
            byte[] fileByte = byteArrayOutputStream.toByteArray();
            fileStr = new String(fileByte, "utf-8");
        }
        Matcher matcher = compile.matcher(fileStr);
        StringBuffer stringBuffer = new StringBuffer();

        //处理找到的图片
        Map imageMap = new HashMap<>();
        while (matcher.find()) {
            String imagePath = matcher.group(2);

            // 压缩并编码图片
            ByteArrayOutputStream newImage=new ByteArrayOutputStream();
            Thumbnails.of(imagePath).scale(SCALE).outputQuality(QUALITY).outputFormat("jpg").toOutputStream(newImage);
            BASE64Encoder encoder = new BASE64Encoder();
            String encode = encoder.encode(newImage.toByteArray()).replace("\r\n","");

            //  转换匹配项
            String imagePathName=imagePath.hashCode()+"";
            encode ="\r\n\r\n"+ "[" + imagePathName + "]:data:iamge/jpg;base64," + encode + "\r\n\r\n";
            imageMap.put(imagePathName, encode);
            matcher.appendReplacement(stringBuffer, matcher.group(1)+"[" + imagePathName + "]\r\n\r\n");
        }
        matcher.appendTail(stringBuffer);
        for (Map.Entry entry : imageMap.entrySet()) {
            stringBuffer.append(entry.getValue());
        }

        //生成新文件
        String parentPath = new File(filePath).getCanonicalPath();
        try (FileWriter fileWriter = new FileWriter(parentPath.replace(".", "-remove."));) {
            fileWriter.write(stringBuffer.toString());
        }

    }
}

 

你可能感兴趣的:(markdown的本地图片转BASE64,一起附在文件中)