base64还原成图片

图片的base64形式还原成图片

前端返回给后端的是图片的base64形式的字符串,后端需要还原成图片,并保存到服务器端。

代码如下:

/**
     * 图片保存到服务器端,用于分享到微信
     * @param jsonObject
     */
    public void serverImg(JSONObject jsonObject){
        // 员工号
        String userId = jsonObject.getString("userId");
        // base64字符串(大概4MB)
        String base = jsonObject.getString("binaryImg");
        //将base64字符串转换为字节数组
        byte[] b1 = base64topng(base);
        String imgFilePath1 = filePath(b1,userId);
    }

    /**
     * 将图片的二进制转换为字符数组
     * @param imageBase64
     * @return
     */
    public static byte[] base64topng(String imageBase64) {
        byte[] b1 = null;
        BASE64Decoder decoder = new BASE64Decoder();
        try{
            if (imageBase64.indexOf("data:image/jpeg;base64,") != -1) {
                b1 = decoder.decodeBuffer(imageBase64.replaceAll("data:image/jpeg;base64,", ""));
            } else {
                if (imageBase64.indexOf("data:image/png;base64,") != -1) {
                    b1 = decoder.decodeBuffer(imageBase64.replaceAll("data:image/png;base64,", ""));
                } else {
                    b1 = decoder.decodeBuffer(imageBase64.replaceAll("data:image/jpg;base64,", ""));
                }
            }
            for (int i = 0; i < b1.length; ++i) {
                if (b1[i] < 0) {// 调整异常数据
                    b1[i] += 256;
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return b1;
    }

    /**
     * 图片保存地址
     * @param b
     * @param userId 当前用户员工编号
     * @return
     */
    public static String filePath(byte[] b, String userId) {
        String imgPath = "";
        try {
            String FilePath ="D:\\image";//新生成的图片
            File f1=new File(FilePath);
            if(!f1.exists()){
                f1.mkdir();
            }
            imgPath = FilePath+"/"+userId+".jpg";
            File f2 = new File(imgPath);
            if(!f2.exists()) {
                f2.createNewFile();
            }
            OutputStream out = new FileOutputStream(imgPath);
            out.write(b);
            out.flush();
            out.close();

        }catch(Exception e) {
            e.printStackTrace();
        }
        return imgPath;
    }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值