Use PhantomJS to implement the Web screenshot Service

Source: Internet
Author: User

Use PhantomJS to implement Web Services
This is a small demand in the first half of the year. We want to capture webpages and save them as images. I have studied a lot of tools, and the results are not satisfactory. It is not a poor display (Canvas, Html2Image, Cobra), or poor performance (such as SWT's Brower ). After finding that no interface browser can meet this condition, I roughly studied PhantomJS and CutyCapt, both of which are Webkit kernels. PhantomJS is more convenient to use, especially on Windows platforms, in Linux, if you need to compile it on the machine after version 2.0 (it may take about three hours to compile it), you have to say that g ++ is a dregs and the same project, compiling in vc is fast. After all, it is a free open-source compiler ). The following introduces PhantomJS with Java code implementation of web technology: 1, Environment preparation 1, PhantomJS Script directory: D:/xxx/phantomjs-2.0.0-windows/bin/phantomjs 2, script: D: /xxx/phantomjs-2.0.0-windows/bin/rasterize. js scripts are provided on the official website, but here I need to describe its high-width design principle: page. viewportSize = {width: 600, height: 600}; this is the default height, that is, 600X600. We recommend that you set the height to a smaller value. Here we set the width: 800, height: 200. In fact, when the height and brightness are not set at the same time, if the actual webpage height is greater than the set value, the image will automatically expand to the high width, until the entire page is displayed (when you want to take a small image, it may be too large by default, which will make the image a lot of blank ). If a high width is set at the same time, the following code will be executed and part of the webpage will be intercepted: page. clipRect = {top: 0, left: 0, width: pageWidth, height: pageHeight}; 3, first use the command line to test: D:/xxx/phantomjs-2.0.0-windows/bin/phantomjs D: /xxx/phantomjs-2.0.0-windows/bin/rasterize. js http://www.qq.com D:/test.png if configured, you should be able to see the generated picture. Of course, you can also configure high-width parameters. After the preceding command, you can add "1000px" or "1000px * 400px. Ii. server code as a web service. These code snippets should be deployed on the server. Of course, you don't have to copy them all. You can use them as needed:

1 package lekkoli. test; 2 3 import java. io. bufferedInputStream; 4 import java. io. bufferedReader; 5 import java. io. byteArrayOutputStream; 6 import java. io. file; 7 import java. io. fileInputStream; 8 import java. io. IOException; 9 import org. apache. log4j. logger; 10 11/** 12 * webpage to image processing class, use external CMD 13 * @ author lekkoli 14 */15 public class PhantomTools {16 17 private static final Logger _ logger = Logger. ge TLogger (PhantomTools. class); 18 19 // private static final String _ tempPath = "/data/temp/phantom _"; 20 // private static final String _ shellCommand = "/usr/local/xxx/phantomjs/usr/local/xxx/rasterize. js "; Linux Command 21 private static final String _ tempPath =" D:/data/temp/phantom _ "; 22 private static final String _ shellCommand =" D: /xxx/phantomjs-2.0.0-windows/bin/phantomjs D:/xxx/phantomjs-2.0. 0-windows/bin/rasterize. js "; 23 24 private String _ file; 25 private String _ size; 26 27/** 28 * constructor 29 * @ parm hash: the directory used for temporary files is unique. 30 */31 public PhantomTools (int hash) {32 _ file = _ tempPath + hash + ". png "; 33} 34 35/** 36 * constructor Class 37 * @ parm hash: Used to uniquely convert the temporary file directory 38 * @ param size the image size, for example, 800px * 600px (the height will be cropped at this time), or 800px (the minimum height = width * 9/16, the height is not cropped) 39 */40 public PhantomTools (int hash, String size) {41 this (Hash); 42 if (size! = Null) 43 _ size = "" + size; 44} 45 46/** 47 * convert the target webpage to an image byte stream 48 * @ param url 49 * @ return byte stream 50 */51 public byte [] getByteImg (string url) throws IOException {52 BufferedInputStream in = null; 53 ByteArrayOutputStream out = null; 54 File file = null; 55 byte [] ret = null; 56 try {57 if (exeCmd (_ shellCommand + url + "" + _ file + (_ size! = Null? _ Size: "") {58 file = new File (_ file); 59 if (file. exists () {60 out = new ByteArrayOutputStream (); 61 byte [] B = new byte [5120]; 62 in = new BufferedInputStream (new FileInputStream (file )); 63 int n; 64 while (n = in. read (B, 0, 5120 ))! =-1) {65 out. write (B, 0, n); 66} 67 file. delete (); 68 ret = out. toByteArray (); 69} 70} else {71 ret = new byte [] {}; 72} 73} finally {74 try {75 if (out! = Null) {76 out. close (); 77} 78} catch (IOException e) {79 _ logger. error (e); 80} 81 try {82 if (in! = Null) {83 in. close (); 84} 85} catch (IOException e) {86 _ logger. error (e); 87} 88 if (file! = Null & file. exists () {89 file. delete (); 90} 91} 92 return ret; 93} 94 95/** 96 * Run CMD command 97 */98 private static boolean exeCmd (String commandStr) {99 BufferedReader br = null; 100 try {101 Process p = runtime.getruntime(cmd.exe c (commandStr); 102 if (p. waitFor ()! = 0 & p. exitValue () = 1) {103 return false; 104} 105} catch (Exception e) {106 _ logger. error (e); 107} finally {108 if (br! = Null) {109 try {110 br. close (); 111} catch (Exception e) {112 _ logger. error (e); 113} 114} 115} 116 return true; 117} 118}

 

Using the above PhantomTools class, you can easily call the getByteImg method to generate and obtain the image content.

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.