java將base64解析圖片保存到本地。


將base64解析圖片保存到本地的兩個方法

    /**
     * base64轉圖片
     * @param base64str base64碼
     * @param savePath 圖片路徑
     * @return
     */
    public static boolean GenerateImage(String base64str, String savePath) {
        //對字節數組字符串進行Base64解碼並生成圖片
        if (base64str == null) {
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解碼
            byte[] b = decoder.decodeBuffer(base64str);
            for (int i = 0; i < b.length; ++i) {
                //調整異常數據
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            //生成jpeg圖片
            OutputStream out = new FileOutputStream(savePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * base64轉圖片
     * @param base64Code base64碼
     */
    public static void convertBase64ToImage(String base64Code){
        BufferedImage image = null;
        byte[] imageByte = null;
        try {
            imageByte = DatatypeConverter.parseBase64Binary(base64Code);
            ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
            image = ImageIO.read(new ByteArrayInputStream(imageByte));
            bis.close();
            File outputfile = new File("d:\\sealImg.jpg");
            ImageIO.write(image, "jpg", outputfile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM