java将base64编码字符串还原为图片

web项目经常需要上传图片,若后台获取到的是base64编码的字符串,就需要将字符串还原为图片了  

String src1 = request.getParameter("src1");
//从页面获取一个base64编码的字符串
byte[] b1 = imageBase64.base64topng(src1);
//将字符串转换为字节数组
String imgFilePath1 = imageBase64.filePath(request, b1);
//将字节数组生成图片
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;
	}
	
	public static String filePath(javax.servlet.http.HttpServletRequest request,byte[] b) {
		String imgPath = "";
		try {
			String FilePath =request.getSession().getServletContext().getRealPath("/upload");//新生成的图片  
	    	File f1=new File(FilePath);
	    	if(!f1.exists()){
	        	f1.mkdir();
	        }
	    	imgPath = FilePath+"/"+UUID.randomUUID().toString()+".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;
	}

 

 

 

你可能感兴趣的:(java)