美文网首页
图片转换base64编码

图片转换base64编码

作者: 刘书生 | 来源:发表于2019-07-23 09:33 被阅读0次
 //图片所存放路径
    private String imagePath = "C:\\Users\\Administrator\\Desktop\\b9715f2a20e612b7";


    /**
     * 需要手动替换一下图片的base64编码
     * @return
     */
    public String imagePath(){
        //1、校验是否为空
        if(imagePath==null || imagePath.trim().length()<=0){
            return "";
        }

        //2、校验文件是否为目录或者是否存在
        File picFile = new File(imagePath);
        if(picFile.isDirectory() || (!picFile.exists())) {
            return "";
        };

        //3、校验是否为图片
        try {
            BufferedImage image = ImageIO.read(picFile);
            if (image == null) {
                return "";
            }
        } catch(IOException ex) {
            ex.printStackTrace();
        }

        //4、转换成base64编码
        String imageStr = "";
        try {
            byte[] data = null;
            InputStream in = new FileInputStream(imagePath);
            data = new byte[in.available()];
            in.read(data);
            BASE64Encoder encoder = new BASE64Encoder();
            imageStr = encoder.encode(data);
        } catch (Exception e) {
            imageStr="";
            e.printStackTrace();
        }
        return imageStr;
    }

相关文章

网友评论

      本文标题:图片转换base64编码

      本文链接:https://www.haomeiwen.com/subject/zrinlctx.html