利用html2canvas截屏后可以生成base64类型的图片,但是这样的图片很明显不能被引用或者被SNS工具来分享。这样就必须截屏后再上传数据到后台服务器端重新保存。
前端js代码
## 生成文章缩略图,用于分类子页显示(目前仅gis页面需要使用) html2canvas(document.body, { onrendered:function(canvas) { var myImage = canvas.toDataURL("image/jpeg"); //并将图片上传到服务器用作图片分享 jQuery.ajax({ type : 'POST', url : '$appRoot/article/image/$articleBean.articleId', data : {data:myImage}, success : function(data){ location.reload(); } }); }, width:1000, height:1250 });
后台java代码:
Base64 base64 = new Base64(); // 实际的图片数据是从 data:image/jpeg;base64, 后开始的 byte[] k = base64.decode(data.substring("data:image/jpeg;base64,".length())); InputStream is = new ByteArrayInputStream(k); String imgFilePath = articleImageSave + File.separator + articleId + ".jpg"; BufferedImage image = ImageIO.read(is); // 缩放,也可直接保存 double ratio = 0.1; 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));