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");
                    }
                });

  總之就是這樣子了,算是蠻簡單的例子吧。

     最后,附上我上傳到scdn的例子

  http://download.csdn.net/download/shuangwj/9561348


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM