1. 程式人生 > 其它 >java base64轉圖片

java base64轉圖片

方法 : 傳入檔案路徑和base64位的編碼

    /**
     * base64轉為圖片
     * @param path
     * 檔案路徑:到資料夾即可,程式碼裡會在資料夾裡生成對應的jpg檔案
     * @param base64
     * @return
     */
    public static String base64ToJpg(String path,String base64){
        // 判斷檔案路徑是否存在
        File filePath = new File(path);
        if (!filePath.exists()){
            filePath.mkdirs();
        }
        // 建立檔案
        String jpgFile = path + "\\" + UUID.randomUUID() + ".jpg";
        File file = new File(jpgFile);
        boolean jpgFileExist = false;
        try {
            jpgFileExist = file.createNewFile();
            log.info("jpg檔案建立成功");
        } catch (IOException e) {
            log.info("jpg檔案建立失敗");
            e.printStackTrace();
        }
        if (jpgFileExist){
            // 解密
            Base64.Decoder decoder = Base64.getDecoder();
            // 去掉base64字首 data:image/jpeg;base64,
            base64 = base64.substring(base64.indexOf(",", 1) + 1, base64.length());
            byte[] b = decoder.decode(base64);
            // 處理資料
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            // 儲存圖片
            try {
                FileOutputStream out = new FileOutputStream(jpgFile);
                out.write(b);
                out.flush();
                out.close();
                // 寫入成功返回檔案路徑
                return jpgFile;
            } catch (FileNotFoundException e) {
                log.info("檔案未找到");
                e.printStackTrace();
            } catch (IOException e) {
                log.info("寫入失敗");
                e.printStackTrace();
            }
        }
        return "檔案不存在";
    }

main方法

   public static void main(String[] args) {
        Map<String, Object> imageCode = getImageCode();
        log.info(imageCode.get("imageCodeKey").toString());
        log.info(imageCode.get("imageCodeBase64").toString());
        String base64 = imageCode.get("imageCodeBase64").toString();
        String filePath = "C:\\Users\\Asus\\Desktop\\temp";
        String res = base64ToJpg(filePath, base64);
        log.info(res);
    }

結果