图片由base64转为链接形式

base64的图片格式在存储时是很占空间的,所以上传服务器后保存图片链接是个很不错的选择;代码如下:

    public String uploadImg(String baseImg){
        String url = "";
        try {
            String rootPath = "";
            String path = "";
            String random = "";
            try {
                //对于base64格式的图片,要去掉开头的部分
                int dex = baseImg.indexOf("base64,");
                baseImg = baseImg.substring(dex + 7);
                //将图片信息转换为字节数组
                byte[] arr = Base64Decoder.decodeToBytes(baseImg);
                random = UUID.randomUUID().toString() + ".jpg";
                String root = PathKit.getWebRootPath();
                path = "/upload/";
                rootPath = root + path;
                File targetDir = new File(rootPath);
                if (!targetDir.exists()) {
                    targetDir.mkdirs();
                }
                OutputStream out = new FileOutputStream(rootPath + random);
                //循环写出,确保文件写完
                for (int i = 0; i < arr.length; i++) {
                    out.write(arr[i]);// 逐字节写文件
                }
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            //测试地址(地址自定义)
            url = "http://localhost:8080/kd_admin/upload/"+ random;
            
        } catch (Exception e) {
            url = null;
            e.printStackTrace();
        }
        return url;
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容