phantomjsをインストールしjavaコードでスクリーンショット

9886 ワード

最近phantomjsの公式サイトを見に行って、phantomjsの学生を深く使うことを提案して公式サイトの例を見ます
≪合計更新|Summary Update|emdw≫:タイムアウト時間を設定できます(コマンド・ライン・パラメータまたはjsファイルに書きます).
phantomjsはマルチスレッドをサポートするのに不便です(phantomjsカーネルを開くたびにメモリなどが消費されます)
js構文をサポートするにはwindowを使用します.Open()設定はサーバなどにフィードバックします.
phantomjsはIO読み取りファイルをサポート
インストール方法:
phantomjsインストールファイルをダウンロードし、関連ディレクトリに直接解凍し、パッケージを解く:tar xvf FileName.tar
ソフト接続の作成便利呼び出し:(ln-sfを使用して強制的に実行された場合)
ln  –s  /root/satanbox/phantomjs/phantomjs-1.9.7/bin/phantomjs  /usr/bin/phantomjs
関連ライブラリのインストール:yum install freetype-devel fontconfig-devel
中国語の文字化けし:インストールコード
centosで実行:yum install bitmap-fonts bitmap-fonts-cjk
ubuntuで実行:sudo apt-get install xfonts-wqy
テスト
phantomjs/home/satanbox/phantomjs/phantomjs-1.9.7/examples/rasterize.js  http://www.baidu.com  /home/satanbox/test/a.png
JAvaコードはphantomjsに代わってスクリーンショットを行います.
コード説明:phantomjsはマルチスレッドのサポートがよくなく、単一スレッドを使用することを提案し、ProcessUtilsのcreateIndexImageメソッドを呼び出してスクリーンショットを行い、3分でプロセスを殺すことができない
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PrintscreenUtil {
	
	private static Logger logger = LoggerFactory.getLogger(ProcessUtils.class);
	public static ConcurrentLinkedQueue<Long>  websiteRunning = new ConcurrentLinkedQueue<Long>();//      pid   

	/**
	 * 
	 * @  :   phantomjs    
	 * @  :
	 * @    : 2016 6 22    5:33:58
	 * @param url
	 * @param imagePath
	 * @return
	 */
	public static byte[] getImage(String url, String imagePath) {
		if (!url.contains("http") && !url.contains("https")) {
			url = "http://" + url;
		}

		Process process = ProcessUtils.createIndexImage(url + "  " + imagePath);
		if (process != null) {
			new Thread(new ClearStream(process.getInputStream())).start();
			new Thread(new ClearStream(process.getErrorStream())).start();
			int currentPid = ProcessUtils.getProPid(process);
			int count = 0;
			int flag = 0;
			while (true) {
				//          
				if (count > 50) {
					logger.info("      ,    " + imagePath);
					ProcessUtils.killProcessByPid(currentPid);
					break;
				}
				try {
					//          
					count++;
					logger.info("      " + count + "     ");
					Thread.sleep(3 * 1000);
				} catch (InterruptedException e) {
					logger.error("           ", e);
					break;
				}

				List<Integer> pidList = ProcessUtils.getProcessPidByName("phantomjs");

				if (pidList != null && pidList.size() > 0) {
					for (Integer pid : pidList) {
						if (pid != null) {
							if (pid.equals(currentPid)) {
								flag = 1;
								break;
							}
						}
					}
				} else {
					flag = 0;
				}
				if (flag == 0) {
					//    
					byte[] imageByte = getImageByte(imagePath);
					return imageByte;
				}
			}

		}

		return null;
	}

	/**
	 *              
	 * 
	 * @param imagePath
	 * @return
	 */
	public static byte[] getImageByte(String imagePath) {
		File file = new File(imagePath);
		byte[] imageByte = null;
		FileInputStream fin = null;
		try {
			imageByte = new byte[(int) file.length()];
			fin = new FileInputStream(file);
			fin.read(imageByte);
			return imageByte;
		} catch (FileNotFoundException e) {
			logger.info(e.getMessage());
		} catch (IOException e) {
			logger.info(e.getMessage());
		} finally {
			if (fin != null) {
				try {
					fin.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return null;
	}

	/**
	 * @  : ClearStream
	 * @  :      
	 */
	private static class ClearStream implements Runnable {
		private InputStream inputStream;

		public ClearStream(InputStream inputStream) {
			this.inputStream = inputStream;
		}

		public void run() {
			BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
			try {
				String line = null;
				while ((line = br.readLine()) != null) {
					if (line != null) {
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {//     
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
コード分割
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
/**
 * @  : ProcessUtils 
 * @  :      
 */
public class ProcessUtils {

	private static Logger logger = LoggerFactory.getLogger(ProcessUtils.class);
	
	/**
	 * @   : getProcessPidByName
	 * @  :           
	 * @param processName
	 * @return
	 */
	public static List<Integer> getProcessPidByName(String processName) {
		List<Integer> pidList = new ArrayList<Integer>();
		Process process;
		String command = "";
		try {
			if (Platform.isWindows()) {
				command = "cmd.exe /c tasklist";
				process = Runtime.getRuntime().exec(command);
				InputStream is = process.getInputStream();
				BufferedReader r = new BufferedReader(new InputStreamReader(is));
				String str = null;
				while ((str = r.readLine()) != null) {
					String id = null;
					Matcher matcher = Pattern.compile(processName + ".exe[ ]*([0-9]*)").matcher(str);
					while (matcher.find()) {
						if (matcher.groupCount() >= 1) {
							id = matcher.group(1);
							if (id != null) {
								Integer pid = null;
								try {
									pid = Integer.parseInt(id);
									pidList.add(pid);
								} catch (NumberFormatException e) {
									e.printStackTrace();
								}

							}
						}
					}
				}
			} else if (Platform.isLinux()) {
				command = "pidof " + processName;
				process = Runtime.getRuntime().exec(command);
				InputStream is = process.getInputStream();
				BufferedReader r = new BufferedReader(new InputStreamReader(is));
				String str = null;
				while ((str = r.readLine()) != null) {
					String [] ids = str.split(" ");
					for(String id : ids){
						if(id != null){
							pidList.add(Integer.parseInt(id));
						}
					}		
				}
			} else {
				return null;
			}
		} catch (IOException e) {
			logger.error("    pid    ");
			e.printStackTrace();
		}
		return pidList;
	}

	/**
	 *     PID
	 * 
	 * @return
	 */
	public static Integer getProPid(Process process) {
		Field f;
		if (Platform.isWindows()) {
			try {
				f = process.getClass().getDeclaredField("handle");
				f.setAccessible(true);
				int pid = Kernel32.INSTANCE.GetProcessId((Long) f.get(process));
				return pid;
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} else if (Platform.isLinux()) {
			try {
				f = process.getClass().getDeclaredField("pid");
				f.setAccessible(true);
				int pid = (Integer) f.get(process);
				return pid;
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} else {
		}
		return null;
	}

	/**
	 * @   : killProcessByPid
	 * @  :   pid    
	 * @param pid
	 */
	public static void killProcessByPid(Integer pid) {
		if (pid != null) {
			String command = "";
			if (Platform.isWindows()) {
				command = "cmd.exe /c taskkill /f /pid " + pid;
			} else if (Platform.isLinux()) {
				command = "kill -9 " + pid;
			} else {
				return;
			}
			try {
				Runtime.getRuntime().exec(command);
			} catch (IOException e) {
				logger.info("   " + pid + "       ,  ,"+e);
			}
		}
	}

	/**
	 *        </p>
	 * phantomjs 
	 *     : /home/satanbox/phantomjs/phantomjs-1.9.7/examples/rasterize.js  </p>
	 *    :http://www.jsjg.gov.cn/ </p>
	 *     : /home/satanbox/test/test.png 1000px*1000px
	 * @    : 2015 12 3    2:08:44
	 * @param imagePath
	 * @return
	 */
	public static Process createIndexImage(String imagePath){
		String command = "";
		if (Platform.isLinux()){
			command = "phantomjs " +  PropertiesInfo.PHANTOMJS_DIR + " " + imagePath + "  1024px*768px";
			try {
				Process process = Runtime.getRuntime().exec(command);
				return process;
			} catch (IOException e) {
				logger.info("         " +  imagePath ,e);
			}
		}
		return null;
	}
	
	/**
	 *    wget  
	 * @    : 2015 12 3    2:09:31
	 * @param command
	 * @return
	 */
	public static Process execWgetCommand(String command){
		
		try {
			Process exec = Runtime.getRuntime().exec(command);
			return exec;
		} catch (IOException e) {
			logger.info("  wget     command:" + command,e);
		}
		
		return null;
	}
	
	/**
	 * @  : Kernel32
	 * @  :     pid
	 */
	static interface Kernel32 extends Library {
		public static Kernel32 INSTANCE = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);

		public int GetProcessId(Long hProcess);
	}
}

もう1つの単一スレッド制御を追加
	public void getImageResult() {
		if (!thread.isAlive() && thread.getState().equals(State.NEW)) {
			thread.start();
		} else if (thread.getState().equals(State.TERMINATED)) {
			logger.error("       ,    ");
			thread = new Thread(new SaveImageResultRunable());
			thread.start();
		} else if (!thread.getState().equals(State.RUNNABLE) && !thread.getState().equals(State.TERMINATED)) {
			logger.info("        ,     :" + thread.getState());
			synchronized (thread) {
				thread.notify();
			}
		}
		logger.info("      :" + thread.getState());
	}

CasperJSのスクリーンショット方式を研究する