base64 和图片 转换

 /**
     * 上传图片
     *
     * @param imgString
     *            图片转换的Base64类的字符串
     * @return
     * @throws Exception
     */
    public static String uploadImg(String imgString) throws Exception {
        String path = null;
        if (BasicTool.isnotBlank(imgString)) {
            BASE64Decoder decoder = new BASE64Decoder();
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgString);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            // 自定义的文件名称
            String trueFileName = String.valueOf(System.currentTimeMillis())
                    + ".png";
            // 设置存放图片文件的路径
            File filePath = new File(File.separator + "opt" + File.separator
                    + "images" + File.separator + "uploadImg" + File.separator
                     + trueFileName);
            path =  filePath.toString();
            System.out.println("存放图片文件的路径:" + path);
            Files.write(filePath.toPath(),b );
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
        }
        return path;
    }

    /**
     * 将图片转为Base64字字符串
     *
     * @param pathString
     *            文件存放路径
     * @return
     * @throws Exception
     */
    public static String showImg(String pathString) throws Exception {
        String imgString = null;
        if (BasicTool.isnotBlank(pathString)) {
            BASE64Encoder encoder = new BASE64Encoder();
            FileInputStream inputStream = new FileInputStream(new File(
                    pathString));
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] by = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(by)) != -1) {
                output.write(by, 0, len);
            }
            output.flush();
            output.close();
            imgString = encoder.encode(output.toByteArray());
        }
        return imgString;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值