Home > Article > Backend Development > How to convert web pages into image format in php
php method to convert web pages into image formats: 1. Install chrome-php/chrome; 2. Install chromium; 3. Implement the conversion logic through the controller.
#php How to convert web pages into image format?
PHP converts the entire web page html into an image and saves it [including scrolling]
1. Install chrome-php/chrome
composer require chrome-php/chrome
2. Install chromium (self-installed) Baidu)
Chromium is a web browser developed by Google. Released under multiple free copyrights such as the BSD license and open source code, the development of Chromium may have started as early as 2006. Chromium is the engine behind Google's Chrome browser, whose purpose is to create a secure, stable and fast universal browser.
3. Controller implementation logic (laravel framework)
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use HeadlessChromium\BrowserFactory; // 测试控制器 class TestController extends Controller { public function index() { // chromium浏览器引擎位置(Mac系统,根据不同系统设置安装) $browserFactory = new BrowserFactory('/Applications/Chromium.app/Contents/MacOS/chromium'); // starts headless chrome $browser = $browserFactory->createBrowser(); // creates a new page and navigate to an url $page = $browser->createPage(); // 自动化访问网页 $url = 'https://www.jianshu.com'; $page->navigate($url)->waitForNavigation(); // 获取浏览器滚动条宽高,用于设置:setViewport $evaluation = $page->callFunction( 'function() { var width = document.body.scrollWidth; var height = document.body.scrollHeight; return [width,height]; }' ); $value = $evaluation->getReturnValue(); $width = $value[0]; $height = $value[1]; $page->setViewport($width, $height)->await(); // wait for operation to complete // take the screenshot (in memory binaries) // 这里如果截取的图片过大,需要设置超时时间或者调整图片质量 $screenshot = $page->screenshot([ 'format' => 'jpeg', // default to 'png' - possible values: 'png', 'jpeg', 'quality' => 100, // only if format is 'jpeg' - default 100 ]); $screenshot->saveToFile(storage_path('/app/example.png')); // 关闭浏览器 $browser->close(); } }
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to convert web pages into image format in php. For more information, please follow other related articles on the PHP Chinese website!