日期:2014-05-16 浏览次数:20648 次
$("#saveImage").click(function() { html2canvas($('#mypics'), { onrendered : function(canvas) { var myImage = canvas.toDataURL("image/jpeg"); //并将图片上传到服务器用作图片分享 $.ajax({ type : "POST", url : '${ctx}/qsupload', data : {data:myImage}, timeout : 60000, success : function(data){ $('#myShowImage').attr('src', '${ctxStatic}/usertemp/'+data+'.jpg'); //服务器上保存图片路径,data是返回的文件名。 } }); } }); });
import org.apache.commons.codec.binary.Base64; @RequestMapping(value = { "${frontPath}/qsupload" }, method = { RequestMethod.POST }) @ResponseBody public String petUpgradeTarget(HttpServletRequest request, String data) { String serverPath = request.getSession().getServletContext() .getRealPath("/"); Base64 base64 = new Base64(); try { //注意点:实际的图片数据是从 data:image/jpeg;base64, 后开始的 byte[] k = base64.decode(data.substring("data:image/jpeg;base64," .length())); InputStream is = new ByteArrayInputStream(k); String fileName = UUID.randomUUID().toString(); String imgFilePath = serverPath + "\\static\\usertemp\\" + fileName + ".jpg"; //以下其实可以忽略,将图片压缩处理了一下,可以小一点 double ratio = 1.0; BufferedImage image = ImageIO.read(is); int newWidth = (int) (image.getWidth() * ratio); int newHeight = (int) (image.getHeight() * ratio); Image newimage = image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH); BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB); Graphics g = tag.getGraphics(); g.drawImage(newimage, 0, 0, null); g.dispose(); ImageIO.write(tag, "jpg", new File(imgFilePath)); return fileName; } catch (Exception e) { return "error"; } }