base64字符串转存图片

	public static void base64StringToImage(String base64String,String fileName,String imgType) {  
        try {  
        	
        	System.out.println(base64String);
        	String imgStr =  base64String.replaceFirst("^data:.*;base64,", "");
        	System.out.println(imgStr);
            byte[] bytes = decoder.decodeBuffer(imgStr);  

            String basePath = System.getProperty("base.dir");
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);  
            BufferedImage bi1 = ImageIO.read(bais);  
            File file = new File(basePath + fileName);
            ImageIO.write(bi1, imgType, file);
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
	
	
	public static String getImgType(String imgStr) {
		 String pattern = "^data:image/(.*);base64,";
		
		 
		 Pattern r = Pattern.compile(pattern);
		 
	      // 现在创建 matcher 对象
	      Matcher m = r.matcher(imgStr);
	      
	      if (m.find( )) {
	          System.out.println("Found value: " + m.group(0) );
	          System.out.println("Found value: " + m.group(1) );
	          //System.out.println("Found value: " + m.group(2) );
	          //System.out.println("Found value: " + m.group(3) ); 
	          return m.group(1);
	       } else {
	    	   return "jpg";
	       }
	}
	
	public static boolean isBase64Img(String imgStr) {
	
		 String pattern = "^data:image/(.*);base64,";
		 Pattern r = Pattern.compile(pattern);
	      // 现在创建 matcher 对象
	     Matcher m = r.matcher(imgStr);
	     return m.find();
	}

图片颜色失真,原因待查 。

你可能感兴趣的:(base64字符串转存图片)