java使用runtime 执行linux中的phantomjs 实现自定义图片大小 屏幕截图

开发中遇到的任务需求是,将html5中的内容替换为实时数据后截图,截图的长宽要求是750*3327,将截图的资源路径返回给前端展示及下载

我的java代码:

// url就是图片的地址,imgPath是图片保存的路径
public static String ScreenShot(String url, String imgPath) throws Exception {
		// phantomjs所在的路径
        String execPath = "/usr/local/phantomjs-2.1.1-linux-x86_64/bin/phantomjs";
        // 自己写的js代码所在的位置
        String jsPath = "/home/java/project/inews/inews_report_read/htmlPath/HotScreenshot.js";

        if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
            execPath = "D:\\测试报告\\bin\\phantomjs.exe";
        }
        // 使用runtime去执行屏幕截图
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(execPath + " " + jsPath + " " + url + " " + imgPath);
        InputStream inputStream = process.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        // 成功后返回的图片位置
        String result = bufferedReader.readLine();
        System.out.println(result);
        return result;
    }

我的js文件代码:

var page = require('webpage').create();
system = require('system');
phantom.cutputEncoding = 'utf-8';
// 设置图片的宽度及高度
page.viewportSize = {width: 750, height: 3327};
page.clipRect = {
    width: 750,
    height: 3327
};
// 设置截图的比列
page.zoomFactor = 2;
var url = system.args[1];
var imgPath = system.args[2];
page.open(url, function (status) {
    var result = {};
    if (status === "success") {
        setTimeout(function () {
//			   page.evaluate(function() {
				  page.render(imgPath);
				  result["status"] = 1;
				  result["file"] = imgPath;
				  console.log(JSON.stringify(result));
				  phantom.exit();
//			   });
        }, 3000);
		// 3000是睡眠时间,要等页面加载完所以需要睡眠
    } else {
        result["status"] = -1;
        console.log(JSON.stringify(result));
        phantom.exit();
    }
});
});

效果图:
截图的大小及比列需要自己在js文件中调整

在这里插入图片描述

遇到的问题及解决逻辑:

首先这个phantomjs是只能根据url来截图的,不能直接根据html截图,所以我就把这个html文件修改实时数据之后放到linux中的静态资源文件夹,并拿到html的url地址,就可以进行截图了

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值