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;
    }

猜你喜欢

转载自blog.csdn.net/weixin_45583648/article/details/120521965