jsp 页面代码
var postImg= new Array(); //多张图片数据集合
//第一张图片的信息
var picName = 'pic1'+parseInt(Math.random()*100000000);
var pic = new Object();
pic.type = 'pic1';
pic.dataUrl = encodeURIComponent(encodeURIComponent(myChart1.getDataURL())); //getDataURL() ie8不支持
pic.name = picName;
postImg.push(pic);
//将图片信息保存在隐藏域中
$('#postImgData').val(encodeURIComponent(encodeURIComponent(JSON.stringify(postImg))));
//form 提交数据
$('#postImgForm').form('submit',{
url: '<%=basePath%>jidi/zlfxAction.do?option=postPic',
success: function(result){
}
});
java 代码
//生成图片
private ActionForward postPic(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception{
PrintWriter pw = response.getWriter();
try {
String postImgData = request.getParameter("postImgData")==null?"":request.getParameter("postImgData");
if(!"".equals(postImgData)){
postImgData = URLDecoder.decode(postImgData, "UTF-8");
postImgData = URLDecoder.decode(postImgData, "UTF-8");
}else{
return (mapping.findForward(null));
}
List<Map<String, Object>> mapList = jsonFormatList(postImgData);
for(int j=0;j<mapList.size();j++){
Map<String, Object> map = mapList.get(j);
JSONObject obj = jsonFormatObject(map.toString());
String name = obj.get("name")==null?"":obj.get("name").toString();
String dataUrl = obj.get("dataUrl")==null?"":obj.get("dataUrl").toString();
if (!StringUtils.isBlank(dataUrl)) {
dataUrl = URLDecoder.decode(dataUrl, "UTF-8");
dataUrl = URLDecoder.decode(dataUrl, "UTF-8");
GenerateImage(dataUrl,"D:/png/"+name+".png");
}
}
pw.write(mapper.writeValueAsString("1"));
pw.flush();
}catch (Exception e) {
e.printStackTrace();
pw.write(mapper.writeValueAsString(new JsonError("出错了:"
+ e.getMessage())));
pw.flush();
throw e;
} finally {
pw.close();
}
return (mapping.findForward(null));
}
/**
* json 字符串转 object对象
*
* @param json
* @return
*/
public JSONObject jsonFormatObject(String json) {
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(json);
JSONObject jsonObject = (JSONObject) obj;
return jsonObject;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//base64字符串转化成图片
public static boolean GenerateImage(String imgStr,String imgPath)
{ //对字节数组字符串进行Base64解码并生成图片
if (imgStr == null) //图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try
{
String[] arr = imgStr.split("base64,");
//Base64解码
byte[] b = decoder.decodeBuffer(arr[1]);
for(int i=0;i<b.length;++i)
{
if(b[i]<0)
{//调整异常数据
b[i]+=256;
}
}
//生成jpeg图片
OutputStream out = new FileOutputStream(imgPath);
out.write(b);
out.flush();
out.close();
return true;
}
catch (Exception e)
{
return false;
}
}