java使用代理 html2canvas 截屏 将页面内容生成图片

Posted xiaoss

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java使用代理 html2canvas 截屏 将页面内容生成图片相关的知识,希望对你有一定的参考价值。

1、html2canvas 生成图片简单又好用,但涉及到跨域就会出现问题,官方给出的解决办法是设置代理。基本原理就是在后端将图片的数据生成base64再返回给前端使用。使canvas画布分析元素的时候像分析本地的一样简单。这就是我的理解。官网给出的只有php的方法,我是照扒了一般java的出来。有写的不好的地方,欢迎大家指正。废话不多说了,先上代码。

@RequestMapping(value="/proxy", method = RequestMethod.GET)
	public  void  getJwd(HttpServletRequest request,HttpServletResponse response){
		String url = request.getParameter("url");
		String callback = request.getParameter("callback");
		if(url != "" && callback != ""){
			try {
				URL urlInfo = new URL(url);
				if(urlInfo.getProtocol().equals("http") || urlInfo.getProtocol().equals("https")){
					HttpURLConnection conn = (HttpURLConnection) urlInfo.openConnection(); 
					String contentType = conn.getContentType();
					if(contentType.equals("image/png") || contentType.equals("image/jpg") || contentType.equals("image/jpeg") || contentType.equals("image/gif") || contentType.equals("text/html") || contentType.equals("application/xhtml")){
						if(request.getParameter("xhr2") != null){
							response.setHeader("Access-Control-Allow-Origin", "*");
							response.setContentType(contentType);
							DataInputStream input = new DataInputStream(conn.getInputStream()); 
							BufferedOutputStream bout = new BufferedOutputStream(response.getOutputStream());
							try {
						      byte b[] = new byte[1024];
						      int len = input.read(b);
						      while (len > 0) {
						        bout.write(b, 0, len);
						        len = input.read(b);
						      }
						    } catch (Exception e) {
						      e.printStackTrace();
						    } finally {
						      bout.close();
						      input.close();
						    }
						}else{
							response.setContentType("application/javascript");
							if(contentType.equals("text/html") || contentType.equals("application/xhtml")){
							}else{
								// 获取数据流生成byte字节
								DataInputStream input = new DataInputStream(conn.getInputStream());
								input.toString();
								byte[] buffer = new byte[1024 * 8]; 
								
								ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); 
								byte[] b = new byte[1024 * 8]; 
								int n;  
					            while ((n = input.read(b)) != -1) {  
					                bos.write(b, 0, n);  
					            }  
					            input.close();  
					            bos.close(); 
					            buffer = bos.toByteArray();  
					            // 将byte转成base64
								BASE64Encoder encode = new BASE64Encoder(); 
								String base64data = encode.encode(buffer);
								base64data = base64data.replaceAll("\r\n","");
								response.getWriter().write(callback+"(‘"+ "data:" + contentType + ";base64," + base64data +"‘)");
							}
						}

 
					}
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} 
		}

  2、前端调用的代码如下:

html2canvas(document.getElementById("aaaaaaa"), {
                    "logging": true, //Enable log (use Web Console for get Errors and Warnings)
                    "proxy": basePath + "canvas/proxy.do",
                    "onrendered": function(canvas) {
                        var img = new Image();
                        img.crossOrigin = "*";
                        img.onload = function() {
                            img.onload = null;
                            //document.body.appendChild(img);
                            $("#Screenshot_show").append(img);
                        };
                        img.onerror = function() {
                            img.onerror = null;
                            if(window.console.log) {
                                window.console.log("Not loaded image from canvas.toDataURL");
                            } else {
                                alert("Not loaded image from canvas.toDataURL");
                            }
                        };
                        img.src = canvas.toDataURL("image/png");
                    }
                });

  总之就是这样子了,算是蛮简单的例子吧。

以上是关于java使用代理 html2canvas 截屏 将页面内容生成图片的主要内容,如果未能解决你的问题,请参考以下文章

html2canvas.js截屏并上传到后台

html2canvas在ios上截屏样式不识别

网页截屏调研记录

手机为啥截屏总是模糊的呢?

html2canvas.js网页截图功能

html2canvas截取不到地图