php网页截图可行方法
一、使用第三方API
https://screenshotlayer.com/
二、使用PHP+CutyCapt实现网页截图
基于Webkit内核,在win10上测试未通过
方法原文:https://www.jb51.net/article/94007.htm
参考资料2:https://blog.csdn.net/changemyself/article/details/8618839
CutyCapt下载地址:http://sourceforge.net/projects/cutycapt/files/cutycapt/
windows CutyCapt不需要安装,直接保存到你的电脑中即可,然后php代码如下写:
<?php /* 网页截图功能,必须安装IE+CutyCapt url:要截图的网页 out:图片保存路径 path:CutyCapt路径 cmd:CutyCapt执行命令 比如:http://你php路径.php?url=//www.jb51.net */ $url=$_GET["url"]; $imgname=str_replace('http://','',$url); $imgname=str_replace('https://','',$imgname); $imgname=str_replace('.','-',$imgname); $out = 'D:/webroot/test/'.$imgname.'.png'; $path = 'D:/webserver/CutyCapt.exe'; $cmd = "$path --url=$url --out=$out"; echo $cmd; system($cmd); ?>
ubuntu下安装cutycapt
1、两条命令搞定
apt-get install cutycapt apt-get install xvfb
2、测试截图(ubuntu18上未测试成功)
xvfb-run --server-args="-screen 0, 1024x768x24" cutycapt --url=http://www.baidu.com --out=baidu.png
xvfb 是通过提供一个类似 X server 守护进程 和 设置程序运行的环境变量 DISPLAY 来提供程序运行的环境
中文乱码问题:
将windows下的中文字体上传至/usr/share/fonts目录,执行下命令fc-cache即可。
三、使用PHP+PhantomJS
基于Webkit内核
http://phantomjs.org/download.html
ubuntu上安装:
apt-get install phantomjs
官方已经列出截图代码(有部分修改)
//PhantomJS网页截屏代码 var page = require('webpage').create(); var args = require('system').args; var pageW = 1366; var pageH = 768; page.viewportSize = { width: pageW, height: pageH }; var url = args[1]; var filename = args[2]; page.open(url, function(status) { if (status !== 'success') { console.log('Unable to load ' + url + ' !'); phantom.exit(); } else { window.setTimeout(function() { page.clipRect = { left: 0, top: 0, width: pageW, height: pageH }; page.render(filename); console.log('finish:', filename); phantom.exit(); }, 1000); } });
以上需要存为snap.js,同时使用以下php代码 exec这个js
php部分
<?php if (isset($_GET['url'])) { set_time_limit(0); $url = trim($_GET['url']); $filePath = md5($url).'.png'; if (is_file($filePath)) { exit($filePath); } $command = "phantomjs snap.js {$url} {$filePath}"; @exec($command); exit($filePath); } ?>
如果字体不美观,可参考此文安装字体:https://www.crazyken.cn/blog/post/426.html
或安装基础中文字体:
apt-get install xfonts-wqy
如果出现:qt.qpa.screen: QXcbConnection: Could not connect to display Could not connect to any X display
等问题,可以
vim /usr/bin/phantomjs
在文件开头加上
export QT_QPA_PLATFORM=offscreen export QT_QPA_FONTDIR=/usr/share/fonts
如果还不行,试试
apt-get install -y build-essential g++ flex bison gperf ruby perl libsqlite3-dev libfontconfig1-dev libicu-dev libfreetype6 libssl-dev libpng-dev libjpeg-dev python libx11-dev libxext-dev
四、puppeteer
https://www.crazyken.cn/blog/post/432.html
五、html2canvas
http://html2canvas.hertzen.com/
貌似是一个浏览器端的工具
六、wkhtmltoimage
安装
wget https://downloads.wkhtmltopdf.org/0.12/0.12.5/wkhtmltox_0.12.5-1.bionic_amd64.deb apt-get install xfonts-75dpi xfonts-base -y dpkg -i wkhtmltox_0.12.5-1.bionic_amd64.deb
使用:将sohu.com首页截图为sohu.jpg文件
wkhtmltoimage www.sohu.com sohu.jpg
查看帮助
wkhtmltopdf -H
https://blog.csdn.net/kindy1022/article/details/7641991
PHP里直接 exec就可以调用生成 然后做图片处理