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 }) @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"; } }
相关推荐
wuychn 2020-08-16
阳光之吻 2020-08-03
sjpeter 2020-07-26
yang0cs 2020-07-04
furongwei 2020-07-04
goodriver 2020-06-17
MichelinMessi 2020-06-13
sapliang 2020-06-12
zhangwentaohh 2020-06-05
swtIrene 2020-06-04
SoarFly00 2020-06-03
TONIYH 2020-05-25
PioneerFan 2020-05-10
Vampor 2020-05-03
xcznb 2020-05-03
huangzonggui 2020-05-01
furongwei 2020-04-25
bluetears 2020-04-23
SoarFly00 2020-04-19