markdown文件中的本地图片转base64编码

markdown文件中的本地图片转base64编码

  • 本地markdown文件上传到csdn博客中本地图片不能上传,于是想到将图片转换成base64格式,嵌入到文章中,然而发现并没有什么卵用,csdn的文件上传长度有限制,导致太长的文件不能完全显示出来。
  • 记录一下本次成果。
  • 这里直接在idea中新建了一个maven项目,使用javaSE内容足够,代码摘自我本人的个人博客项目Abner的个人博客后台
  • 代码如下
package com.abner.pojo;

import java.io.*;
import java.util.Base64;

public class Main {
    public static void main(String[] args) {
        String newMd=displayArticle(args[0]);
        String newPath=args[0].split(".md")[0]+"_Upload.md";//args的第一个参数作为目标md文件的路径
        try{
            File file =new File(newPath);
            if(!file.exists()){
                file.createNewFile();
            }
            FileWriter fileWritter = new FileWriter(file.getName());
            fileWritter.write(newMd);
            fileWritter.close();
            System.out.println("finish");
        }catch(IOException e){
            e.printStackTrace();
        }
    }
 
    public static String displayArticle(String path){//本方法完成从md文件中寻找图片本地链接并转码为base64编码后return 新的String内容。
        InputStreamReader isr = null;
        String encoding="UTF-8";
        BufferedReader bufferedReader = null;
        String basePath=null;
        //找到md文件的父目录,更简单的做法是使用:
        /*
                 File dest=new File(path);
                dest.getParentFile();
                来获取
        */
        for(int i=path.length();i>0;i--){
            if(path.substring(i-1,i).equals("/")){
                basePath=path.substring(0,i);
                break;
            }
            if(i==1){
                basePath="./";
            }
        }
        File file=new File(path);
        StringBuffer sb = new StringBuffer();
        try {
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file),encoding);//考虑到编码格式
                bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                //the base64 encoder makes photos to base64 code,not the "src=*.png/jpg" patten
                final Base64.Encoder encoder = Base64.getEncoder();
                while((lineTxt = bufferedReader.readLine()) != null){
                    if (lineTxt.contains("<img src=")){//第一种图片格式
                        String imgName=lineTxt.split("\"")[1];
                        String imgType=imgName.split("\\.")[1];
                        String encodedText=generateBase64ForImg(basePath,imgName,encoder);
                        lineTxt=getFullImgHTMLLabel(imgType,encodedText);
                    }else if((lineTxt.contains("![")&&lineTxt.contains("]("))){//第二种图片格式
                        String imgName=lineTxt.split("]\\(")[1];
                        String basePathAlias=basePath;//if image name contains '/',
                        // it means that it doesn't saved in the same directory with the md file.
                        // so we need the absolute path.
                        if (imgName.contains("/")){
                            basePathAlias="";
                        }
                        imgName=imgName.substring(0,imgName.length()-1);
                        String imgType=imgName.split("\\.")[1];
                        String encodedText=generateBase64ForImg(basePathAlias,imgName,encoder);
                        lineTxt=getFullImgHTMLLabel(imgType,encodedText);
                    }
                    sb.append(lineTxt);
                    sb.append("\n");
                }
                read.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    //only called by displayArticle 将base64编码图片组合成md认识的格式
    public static String getFullImgHTMLLabel(String imgType, String encodedText){
        return "<img src=\"data:image/"+imgType+";base64,"+encodedText+"\" />";
    }

    //only called by display...  真正的图片转码函数
    public static String generateBase64ForImg(String basePath, String imgName, Base64.Encoder encoder) throws Exception {
        FileInputStream fis=new FileInputStream(basePath+imgName);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bb=new byte[1024];
        int length=0;
        while((length=fis.read(bb))!=-1){
            baos.write(bb,0,length);
        }
        byte[] imgBinary=baos.toByteArray();
        String encodedText = encoder.encodeToString(imgBinary);
        return encodedText;
    }
}
  • 上述代码经过测试无误后使用maven的package命令打包,注意打包过程中可能提示java版本相关错误。pom文件加上如下内容:
    <properties>
        <java.version>12</java.version>
        <maven.compiler.source>12</maven.compiler.source>
        <maven.compiler.target>12</maven.compiler.target>
    </properties>
  • 之后在target文件夹中找到对应的jar包就可以使用
java -jar yourJar.jar 123.md
  • 实际测试发现生成的文件很大,不能完全上传,不知道有没有别的办法解决。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值