解码Base64,并保存图片至本地

五一去了具有诗情画意的城市---杭州,今天是假期结束后回来上班的第一天,玩饱之后回来,确实精神抖擞了不少;

前段时间开发了有关电子签名的需求,其中有个关于解码Base64图片的知识点,值得关注一下;

情况是这样的:

我在签字板上 , 签完名并点击确定之后,生成的图片路径是base64格式的,领导想将签名生成的图片保存在本地,那么问题的重点来了,怎么样将base64格式的图片保存至本地;

下面一朵代码是我的解决方案:

@Test
	public void base64(){
		String imgStr = "data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAABRCAYAAACXMekVAAASFElEQVR4Xu3dBbDsynEG4N9hZmZmZnaYmdlhZqpgJXbYYWZmZmaww8yJw8zMWN+rmdSU3oKklXa1e6arbt17z5FGM635p7l1n3TqHOgc2MuB+3TedA50DuznQAdI3x2dAwc40AHSt0fnQAdI3wMrcuDhk/jzDys+42JDdwlyMdbfzIO/PcljJXlgkq+/mVWVhXSA3NobPe96XivJ15ZHAof/3xR1gNzU6zz7Yl4xybeVp/55kic4+wxWfmAHyMoMvgPD/1mSxy/rBJjvuKU1d4Dc0tu8zFq+N8lLlUd/ZJL3v8w01nlqB8g6fL1Lo356krcvC/7HJE+a5O9vhQEdILfyJi+3jldIwpNV6UWSPOhy01n2yR0gy/LzLo72cEm+KslzJ/m1JK+S5D9uhREdILfyJi+7jkdJ8sRJfveWwIGlHSC7N9bDJnmEJP+c5H8uu/f60y/JgQ6Qe3P/MZN8VpInS8IA/eJLvqD+7MtyoAPk3vx/pySfUn78E0leJgnvTKc7yIE5AHHPsyV5tCQPTvLfN8a3ZyjGpmX9e5L7JgGUTneQA3MA8rRJfjLJIyV51ySfuSDfzIfBxwtic16K2uDXDyd56ST/eanJ9OdejgNzAPKeST62TPmfkkgv+JEFlmAur5/k3Yo3xL8vRfdL8jlJGOvobZN89qUmc0XPfc4kf5pE+slN0ByAyLv56SRPUjjw60mef2Y9wEMVSfQ4Sd47yVuW2gJDv3mSL7wQlx+3qI9PU57/K0leNMnfXmg+1/DYD0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QAfIUpzs49wkB/4P6ctJf+JxZ3EAAAAASUVORK5CYII=";
		String imgFilePath = "D:/youarebeautiful";
		String imgFileName = "/20170503.jpg";
		
		File file = new File(imgFilePath);  

		  if(!file.exists()){//文件根目录不存在时创建  
	            new File(imgFilePath).mkdirs();  
	        } 
		
		System.out.println("图片完整路径:"+imgStr);
		System.out.println("截取图片路径base64部分内容:"+imgStr.substring(22));

		// 图像数据为空
		 if (imgStr == null){
			 System.out.println("imgStr is null");
		 } 
	        BASE64Decoder decoder = new BASE64Decoder();
	        try {
	            // Base64解码
	            byte[] bytes = decoder.decodeBuffer(imgStr.substring(22));
	            
	            System.out.println("bytes的长度:"+bytes.length);
	            
	            for (int i = 0; i < bytes.length; ++i) {
	                if (bytes[i] < 0) {// 调整异常数据
	                    bytes[i] += 256;
	                }
	            }
	            // 生成jpg图片
	            OutputStream out = new FileOutputStream(imgFilePath+imgFileName);
	            out.write(bytes);
	            out.flush();
	            out.close();
	        } catch (Exception e) {
	        	
	        }
	}

  

复制代码即可一试 , 拿走 , 不谢~

posted @ 2017-05-03 15:20  存钱罐  阅读(2346)  评论(0编辑  收藏  举报