Java implementation of Web screenshot function (based on PHANTOMJS)

Source: Internet
Author: User

The company recently had a demand: the user's first measurement of body information and the last measurement of the information compared, and need to cut the contrast of the data into a picture can be sent to the user (need to do not open the page in real-time to the Web page and then save to the server, return to the image address), Through some articles on the Internet, we can find the following ways to realize: reference article 60761614

    • Robot
    • Use JNI to invoke third-party, C + + components
    • Djnativeswing components
    • Using Html2canvas
    • Using Html2image
    • Phantomjs

Using the PHANTOMJS,PLANTOMJS is a JavaScript-based WebKit kernel Headless browser that doesn't have a display interface, and you can do things based on WebKit browser. PLANTOMJS provides such as CSS selectors, Dom manipulation, JSON, HTML5, Canvas, SVG, and more. Phantomjs is useful for a wide range of applications, such as network monitoring, Web screenshots, page access automation, Web testing without a browser, and only a screenshot of the Web page. PLANTOMJS can be downloaded through the official website http://phantomjs.org/download.html, also can pass (only Windows version): https://pan.baidu.com/s/ 1EVX1RPX7GY0RGVEI6OHCWG Password: brb4 download, after decompression can see

The script examples folder under Rasterize.js is as follows:

varpage = require (' webpage '). Create (), System= Require (' System '), address, output, size;if(System.args.length < 3 | | system.args.length > 5) {Phantom.exit (1);} Else{Address= System.args[1];//Incoming URL addressoutput = system.args[2];//address of the output picturePage.viewportsize = {width:800, height:1800};//Custom definition Width height    if(System.args.length > 3 && system.args[2].substr ( -4) = = = ". pdf") {size= System.args[3].split (' * ')); Page.papersize= Size.length = = = 2? {width:size[0], height:size[1], margin: ' 0px '}: {format:system.args[3], Orientation: ' Portrait ', margin: ' 1cm ' }; } Else if(System.args.length > 3 && system.args[3].substr ( -2) = = = = "px") {size= System.args[3].split (' * ')); if(Size.length = = 2) {PageWidth= parseint (size[0], 10); PageHeight= parseint (size[1], 10); Page.viewportsize={width:pagewidth, height:pageheight}; Page.cliprect= {top:0, left:0, Width:pagewidth, height:pageheight}; } Else{Console.log ("Size:", system.args[3]); PageWidth= parseint (system.args[3], 10); PageHeight= parseint (PageWidth * 3/4, 10); Its as good an assumption as any console.log ("PageHeight:", pageheight);        Page.viewportsize = {width:pagewidth, height:pageheight};    }} 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 (1);                } else {window.settimeout (function () {page.render (output);            Phantom.exit ();        }, 200); }    });}

Address = system.args[1];//Incoming URL addresses

output = system.args[2];//The address of the image
Page.viewportsize = {width:800, height:1800};//custom definition width high
Writing Java code
ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;/*** @Description: Converted to image according to Web address * @Author: admin * @CreateDate: June 22, 2018*/ Public classPhantomtools {Private StaticString TempPath = "d:/temp/img";//Picture Save Directory    Private StaticString BLANK = ""; //The following content can be configured in the configuration file    Private StaticString binpath = "D:/tooles/phantomjs/phantomjs-2.1.1-windows/bin/phantomjs.exe";//Plugin Introduction Address    Private StaticString Jspath = "D:/tooles/phantomjs/phantomjs-2.1.1-windows/examples/rasterize.js";//JS Introduction Address//Execute cmd command     Public Staticstring cmd (string imgagepath, string url) {returnBinPath + blank + jspath + blank + URL + blank +Imgagepath; }    //Close Command     Public Static voidClose (Process process, BufferedReader BufferedReader)throwsIOException {if(BufferedReader! =NULL) {bufferedreader.close (); }        if(Process! =NULL) {Process.destroy (); Process=NULL; }    }    /**     * @paramUserId *@paramURL *@throwsIOException*/     Public Static voidprinturlscreen2jpg (String URL)throwsioexception{String Imgagepath= temppath+ "/" +system.currenttimemillis () + ". png";//Picture Path//running external programs in Java using the runtime and process classesProcess Process =runtime.getruntime (). EXEC (cmd (imgagepath,url)); InputStream InputStream=Process.getinputstream (); BufferedReader Reader=NewBufferedReader (NewInputStreamReader (InputStream)); String tmp= "";  while(TMP = Reader.readline ())! =NULL) {close (Process,reader); } System.out.println ("Success"); }         Public Static voidMain (string[] args)throwsioexception {String URL= "https://www.baidu.com/";//take Baidu homepage as an examplephantomtools.printurlscreen2jpg (URL); }}

effect, width and height can be adjusted according to your needs in JS

Java implementation of Web screenshot function (based on PHANTOMJS)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.