1. 程式人生 > >[JavaWeb]將Web頁面內容生成圖片

[JavaWeb]將Web頁面內容生成圖片

在工作中遇到一個需求,是要將Web頁面內容生成一張圖片,然後匯出下載。

下面是四種不同的實現方式:

  • (1)此方法需要用到html2image-0.9.jar
    /**
     * html2image-0.9.jar
     * 
     * HtmlImageGenerator 常用方法
     * 
     * loadUrl(url) - (從url載入html)
     * loadHtml(html) - (載入本地html)
     * saveAsImage(file) - (以圖片形式儲存html)
     * saveAsHtmlWithMap(file, imageUrl) - (建立一個HTML檔案包含客戶端image-map)
     *
     * getLinks() - (列出所有在HTML文件的連結和相應href、目標、頭銜、位置和尺寸)
     * getBufferedImage() - (獲得awt,html緩衝後的圖片)
     * getLinksMapMarkup(mapName) - (HTML程式碼段裡獲得的客戶端image-map <地圖>產生的連結)
     *
     * get/setOrientation(orientation) -  (get/set文字定位)
     * get/setSize(dimension) -  (設定生成圖片大小)
     */

舉例:

        HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
        imageGenerator.loadUrl("http://www.baidu.com"); 
        imageGenerator.saveAsImage("d:/hello-world.png");  
        imageGenerator.saveAsHtmlWithMap("hello-world.html", "hello-world.png");
  • (2)此方法需要用到Cobra.jar
        JFrame window
= new JFrame(); HtmlPanel panel = new HtmlPanel(); window.getContentPane().add(panel); window.setSize(600, 400); window.setVisible(true); new SimpleHtmlRendererContext(panel, new SimpleUserAgentContext()) .navigate("http://www.baidu.com"); BufferedImage image
= new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_ARGB); // paint the editor onto the image SwingUtilities.paintComponent(image.createGraphics(), panel, new JPanel(), 0, 0, image.getWidth(), image.getHeight()); // save the image to file ImageIO.write((RenderedImage) image, "png", new File("html.png"));
  • (3) 此方法不需要任何相關Jar支援
    /**
     * 方法詳解:該方法利用Robat提供的強大桌面操作能力
     *          硬性呼叫瀏覽器開啟指定網頁,並將網頁資訊儲存到本地。
     * 優勢:簡單易用,不需要任何第三方外掛。
     * 缺點:不能同時處理大量資料,技術含量過低,屬於應急型技巧。       
     * @throws URISyntaxException 
     * @throws IOException 
     * @throws MalformedURLException 
     * @throws AWTException 
     * 
     */
    public static void test3() throws MalformedURLException, 
            IOException, URISyntaxException, AWTException{
        //此方法僅適用於JdK1.6及以上版本  
        Desktop.getDesktop().browse(  
                new URL("http://www.baidu.com").toURI());  
        Robot robot = new Robot();  
        robot.delay(10000);  
        Dimension d = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());  
        int width = (int) d.getWidth();  
        int height = (int) d.getHeight();  
        //最大化瀏覽器  
        robot.keyRelease(KeyEvent.VK_F11);  
        robot.delay(2000);  
        Image image = robot.createScreenCapture(new Rectangle(0, 0, width,  
                height));  
        BufferedImage bi = new BufferedImage(width, height,  
                BufferedImage.TYPE_INT_RGB);  
        Graphics g = bi.createGraphics();  
        g.drawImage(image, 0, 0, width, height, null);  
        //儲存圖片  
        ImageIO.write(bi, "jpg", new File("d:/111.jpg"));  
    }
  • (4) 使用H5技術,將頁面截圖,傳入後臺
    前端處理
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
        <script type="text/javascript" src="./jquery-1.9.1.js"></script>
        <script type="text/javascript" src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>
        <script  type="text/javascript" >
        $(document).ready( function(){
                $(".example1").on("click", function(event) {
                        event.preventDefault();
                        html2canvas(document.body, {
                        allowTaint: true,
                        taintTest: false,
                        onrendered: function(canvas) {
                            canvas.id = "mycanvas";
                            //document.body.appendChild(canvas);
                            //生成base64圖片資料
                            var dataUrl = canvas.toDataURL();

                            var newImg = document.createElement("img");
                            newImg.src =  dataUrl;
                            document.body.appendChild(newImg);
                        }
                    });
                }); 

        });

        </script>
    </head>
    <body>

        Hello!
        <div class="" style="background-color: #abc;">
            測試html5頁面截圖
            <br>jsjtt.com
        </div>
        <textArea id="textArea" col="20" rows="10" ></textArea>
        <input class="example1" type="button" value="button">
        生成介面如下:


    </body>
</html>

後臺處理

    /**
     * 使用H5 CANVAS技術,解析當前頁面並且生成Base64資料傳入後臺,後臺將資料生成圖片
     * @throws IOException
     */
    public static void test4() throws IOException {
        String base64ImgData = "後臺傳過來的Base64資料" ;
        String filePath = "d:/11.jpg";
        convertBase64DataToImage(base64ImgData, filePath);
    }


    /** 
     * 把base64圖片資料轉為本地圖片 
     * @param base64ImgData 
     * @param filePath 
     * @throws IOException 
     */  
    public static void convertBase64DataToImage
            (String base64ImgData,String filePath) throws IOException {  
        BASE64Decoder d = new BASE64Decoder();  
        byte[] bs = d.decodeBuffer(base64ImgData);  
        FileOutputStream os = new FileOutputStream(filePath);  
        os.write(bs);  
        os.close();  
    }