热门关键字:
jquery > jquery教程 > java > java实现base64生成图片和使用详解

java实现base64生成图片和使用详解

1203
作者:管理员
发布时间:2015/9/24 16:48:42
评论数:0
转载请自觉注明原文:http://www.jq-school.com/Show.aspx?id=715

java实现base64生成图片和使用详解

java实现base64生成图片和使用详解

/**
 * @Descriptionmap 对字节数组字符串进行Base64解码并生成图片
 * @author temdy
 * @Date 2015-09-24
 * @param base64 图片Base64数据
 * @param path 图片路径
 * @return
 */
public static boolean base64ToImage(String base64, String path) {// 对字节数组字符串进行Base64解码并生成图片
	if (base64 == null){ // 图像数据为空
		return false;
	}
	BASE64Decoder decoder = new BASE64Decoder();
	try {
		// Base64解码
		byte[] bytes = decoder.decodeBuffer(base64);
		for (int i = 0; i < bytes.length; ++i) {
			if (bytes[i] < 0) {// 调整异常数据
				bytes[i] += 256;
			}
		}
		// 生成jpeg图片
		OutputStream out = new FileOutputStream(path);
		out.write(bytes);
		out.flush();
		out.close();
		return true;
	} catch (Exception e) {
		e.printStackTrace();
		return false;
	}
}

用法:
1、获取图片类型
SimpleDateFormat df1 = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String fn = df1.format(new Date());				
String base64 = entity.get("base64").toString();
String imgT = base64.split(",")[0];
if(imgT.indexOf("jpeg") > 0 || imgT.indexOf("jpg") > 0){
	fn = fn+".jpg";
}else if(imgT.indexOf("png") > 0){
	fn = fn+".png";
}else{
	fn = fn+".bmp";
}
2、上传图片
String path = request.getSession().getServletContext().getRealPath("upload")+"/"+fn;
base64 = base64.split(",")[1];
if (StrUtils.base64ToImage(base64, path)){
	//上传成功操作
}	





如果您觉得本文的内容对您的学习有所帮助:支付鼓励



关键字:java base64 生成图片 base64ToImage BASE64Decoder
友荐云推荐