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

本文介绍了一种从Base64编码字符串还原为图片的方法,适用于Web项目中图片的上传需求。具体步骤包括:获取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;
	}

 

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值