html2canvas截屏后上传到服务器端(springmvc3)

利用html2canvas截屏后可以生成base64类型的图片,但是这样的图片很明显不能被引用或者被SNS工具来分享。这样就必须截屏后再上传数据到后台服务器端重新保存。 

前端js代码: 

$("#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 })@ResponseBodypublic 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";}}

html2canvas截屏后上传到服务器端(springmvc3),古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。