Google Analytics

2015年8月5日 星期三

使用PhantomJS實作網頁截圖功能2

承上篇(使用PhantomJS實作網頁截圖功能)

是之前rasterize.js產生網頁截圖時會在指定的路徑下產生實體檔案,但有些情況下也許不希望有這些圖片檔案產生(而希望直接render到網頁中)。此時就需要改寫原本的script。

關鍵API

使用renderBase64()的方法會把原本要產生的圖片用base64的編碼方式轉成字串,可以列印至 console,伺服器端的程式再去讀此字串並以base64解碼。

page.renderBase64('PNG');

改寫網頁截圖script

改寫PhantomJS附的網頁截圖sample code,放在PhantomJS目錄下的examples/rasterize.js:
var page = require('webpage').create(),
    system = require('system'),
    address, output, size;

if (system.args.length < 3 || system.args.length > 5) {
    console.log('Usage: screenshot.js URL filename [imagewidth*imageheight|paperwidth*paperheight|paperformat] [zoom]');
    console.log('  image (png output) examples: "1024*768"');
    console.log('  paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"');
    phantom.exit(1);
} else {
    address = system.args[1];
    output = system.args[2];
    var clipRect = null;
 
    page.viewportSize = { width: 600, height: 600 };
    if (system.args.length > 3) {
        size = system.args[3].split('*');
     
        clipRect = {top: 0, left:0, width: size[0], height: size[1]};
    }
    if (system.args.length > 4) {
        page.zoomFactor = system.args[4];
    }
 
    page.open(address, function (status) {
        if (status !== 'success') {
            console.log('Unable to load the address!');
            phantom.exit();
        } else {
            window.setTimeout(function () {              
                try {
                    if (clipRect) {
                        page.clipRect = clipRect;
                    }

                    var base64 = page.renderBase64(output);
                    console.log(base64);
                } catch (e) {
                    console.log('Failed to capture screenshot as ' + output + ': ' + e, "error");
                }
             
                phantom.exit();
            }, 200);
        }
    });
}

伺服機端(Java Servlet)程式

       try {
            long startTime = System.currentTimeMillis();
           
            String targetUrl = "http://www.google.com.tw/";
            String phantomExeFileName ="C:/application/phantomjs-1.9.7/phantomjs.exe";
            String phantomJsFileName ="C:/application/phantomjs-1.9.7/myJs/screenshotBase64.js";
            
            File phantomExeFile = new File(phantomExeFileName);
            File phantomJsFile = new File(phantomJsFileName);
            String imageSize = "1024*768";
           
                String execCommand = String.format("%s %s %s %s %s",
                            phantomExeFile.getAbsolutePath(),
                            phantomJsFile.getAbsolutePath(),
                            (targetUrl == null) || (targetUrl.length() ==0) ? "": targetUrl,
                            "png",
                             imageSize
                        ).trim();
               
                System.out.println(String.format("execCommand = [%s]", execCommand));
               
              Scanner scanner = new Scanner(Runtime.getRuntime().exec(execCommand).getInputStream()).useDelimiter("\\A");
              String cmdout =  scanner.hasNext() ? scanner.next() : "";
              System.out.println(String.format("cmdout = [%s]", cmdout));
             
                byte[] outImg = null;
               
                if ((cmdout != null) && (cmdout.length() > 0)) {
                    outImg = Base64.decodeBase64(outImg);
                }
                 
                OutputStream out = resp.getOutputStream();
               
                if(outImg != null) {
                    InputStream is = new ByteArrayInputStream(outImg);
                    resp.setContentType("image/png");
                    resp.setContentLength(outImg.length);
                    byte[] buf = new byte[4096];
                    while(true) {
                        int r = is.read(buf, 0, buf.length);
                        if(r == -1) break;
                        out.write(buf, 0, r);
                    }
                    is.close();
                    out.flush();
                }             

                long endTime = System.currentTimeMillis();
                System.out.println("total "new Double((endTime - startTime) / 1000) + " seconds");
               
        } catch (Exception e) {
            logger.error("main() - exception: ", e);
        }
       

        return resp;