截取屏幕截图并返回servlet?

时间:2015-01-27 03:19:29

标签: java servlets

我试图截取网页的截图并从这样的servlet返回:

<img src="http://localhost:8080/image">

这在很大程度上起作用。我正在使用phantomjs,从桌面打开时产生的png显示正常。当使用img标签显示它时,它会出现但是有粉红色调?

我使用以下代码

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String phantomjsHome = "C:\\phantomjs-1.9.8-windows\\";
    String phantomjsRasterizeScript = phantomjsHome + "examples\\rasterize.js";
    String url = "http://localhost/";
    String file = "C:\\index.png";

ProcessBuilder pb = new ProcessBuilder(phantomjsHome + "phantomjs", phantomjsRasterizeScript, url, file);
ProcessBuilder.Redirect error = pb.redirectError();
ProcessBuilder.Redirect out = pb.redirectOutput();
ProcessBuilder.Redirect in = pb.redirectInput();
Process process = pb.start();

try {
    process.waitFor();
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

response.setContentType("image/jpeg");

String pathToWeb = getServletContext().getRealPath(File.separator);
File f = new File("C:\\index.png");
BufferedImage bi = ImageIO.read(f);
OutputStream out1 = response.getOutputStream();
ImageIO.write(bi, "jpg", out1);
out1.close();

}

是否有一些我错过的导致粉红色调的东西?另外,有没有人知道如何使phantomjs只截取div的截图或者有非phantomjs解决方案?

谢谢!

1 个答案:

答案 0 :(得分:0)

答案就在我面前,我正在渲染PNG,但试图返回一个PNG。我渲染为JPEG并返回它,所有都解决了。谢谢!