Java中通过图片路径转base64格式,之后转回图片格式在下载到本地

修改一下BASE64Decoder decoder = new BASE64Decoder();打包有些可能会出现问题,修改为Base64.Decoder decoder = Base64.getDecoder();

1.图片转为base64格式代码

File file = new File("C:\\Users\\1\\Desktop\\123.png");
        byte[] data = null;
        InputStream inputStream = new FileInputStream(file);
        // 读取图片字节数组
        try{
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = inputStream.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
        } catch (
                IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String faceBinaryData = java.util.Base64.getEncoder().encodeToString(data);
        System.out.println(faceBinaryData);

2.通过base64转为图片下载下来

private static String GenerateImage(String base64str, String savePath){
        try {
            //对字节数组字符串进行Base64解码并生成图片
            if (base64str == null || base64str.equals("")) {
                throw new XException("传入的图片base64为空串!");
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String path = savePath + "/" +simpleDateFormat.format(new Date());;
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
//            BASE64Decoder decoder = new BASE64Decoder();
			Base64.Decoder decoder = Base64.getDecoder();

            //Base64解码
            byte[] b = decoder.decodeBuffer(base64str);
            for (int i = 0; i < b.length; ++i) {
                //调整异常数据
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            File tempFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), ".png", file);

            FileOutputStream outputStream = new FileOutputStream(tempFile);
            outputStream.write(b);
            outputStream.flush();
            outputStream.close();
            int indexOf = tempFile.getPath().indexOf("Desktop");
            return tempFile.getPath().substring(indexOf - 1).replaceAll("\\\\","/");

        }catch (Exception e) {
            return  null;
        }
    }

你可能感兴趣的:(java,开发语言)