echars 生成多張圖片
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;
}
}