头像截取裁剪后图片保存,(base64数据)形式保存到数据库和文件
http://blog.youkuaiyun.com/qq_36410795/article/details/72652027
前端代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
pageContext.setAttribute("APP_PATH",request.getContextPath());
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript"
src="${APP_PATH }/static/js/jquery-1.12.4.min.js"></script>
</head>
<body>
<img id="image"src=""/>
<br/>
<input type="file"οnchange="selectImage(this);"/>
<br/>
<input type="button"οnclick="uploadImage();"value="提交"/>
<script>
var image = '';
function selectImage(file){
if(!file.files || !file.files[0]){
return;
}
var reader = new FileReader();
reader.onload = function(evt){
document.getElementById('image').src = evt.target.result;
//
图片转化成base64字符串
image = evt.target.result;
}
reader.readAsDataURL(file.files[0]);
}
function uploadImage(){
image = JSON.stringify(image)
$.ajax({
type:'POST',
url: '${APP_PATH}/goodsinfoController/test',
data: {base64: image},
async: false,
dataType: 'json',
success: function(data){
console.log(data);
if(data.code==100){
alert('上传成功');
}else{
alert('上传失败');
}
},
error: function(err){
alert('网络故障');
}
});
}
</script>
</body>
</html>
public class Base64
{
//图片转化成base64字符串
public static String GetImageStr(String imageName)
{//将图片文件转化为字节数组字符串,并对其进行Base64编码处理
String imgFile = imageName;//待处理的图片
InputStream in = null;
byte[] data = null;
//读取图片字节数组
try
{
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
//对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);//返回Base64编码过的字节数组字符串
}
//base64字符串转化成图片
public static boolean GenerateImage(String imgStr,String imageName)
{ //对字节数组字符串进行Base64解码并生成图片
if (imgStr == null) //图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try
{
//Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for(int i=0;i<b.length;++i)
{
if(b[i]<0)
{//调整异常数据
b[i]+=256;
}
}
//生成jpeg图片
String imgFilePath = imageName;//新生成的图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
}
catch (Exception e)
{
return false;
}
}
}