java base64工具类 保存图片

该方法用于base64解码,并存储图片 


    // 图片路劲层级分隔符
    private static String separator = "/";
    public String saveImg(String baseImg,String saveName) throws Base64DecodingException {
        //定义一个正则表达式的筛选规则,为了获取图片的类型
        String rgex = "data:image/(.*?);base64";
        String type = getSubUtilSimple(baseImg, rgex);
        //去除base64图片的前缀
        baseImg = baseImg.replaceFirst("data:(.+?);base64,", "");
        byte[] b;
        byte[] bs;
        OutputStream os = null;
        String fileName = "";

        //把图片转换成二进制
        b = Base64.decode(baseImg.replaceAll(" ", "+"));
        //生成路径
        //获取项目classes/static的地址
        String staticPath = ClassUtils.getDefaultClassLoader().getResource("static").getPath();
        //文件名称
        String uploadFileName = UUID.randomUUID().toString();
        // 图片存储目录及图片名称
        String url_path = "img" + File.separator;
        //图片保存路径
        String path = staticPath + File.separator + url_path;
        // 访问路径=静态资源路径+文件目录路径
        String visitPath ="static/" + url_path;
        //随机生成图片的名字,同时根据类型结尾
        fileName = saveName + "." + type;
        File file = new File(path);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
        File imageFile = new File(path + "/" + fileName);
        BASE64Decoder d = new BASE64Decoder();
        // 保存
        try {
            bs = d.decodeBuffer(Base64.encode(b));
            os = new FileOutputStream(imageFile);
            os.write(bs);
        } catch (IOException e) {
            e.printStackTrace();

        }finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.getLocalizedMessage();
                }
            }
        }

        return "img" +  separator + fileName;
    }

————————————————————上文出自胖胖,转载请附带原文链接

后续更新自学的方法,以及java知识总结
我是哪怕前路坎坷,也不愿负年轻的菜狗,自学之路,共勉

你可能感兴趣的:(java)