玉兔远程控制 0.1.0-bate5
载入中...
搜索中...
未找到
CaptureFullPage.cpp
1// Author: Kang Lin <kl222@126.com>
2
3#include <QTimer>
4#include <QPainter>
5#include <QLoggingCategory>
6#include "CaptureFullPage.h"
7
8static Q_LOGGING_CATEGORY(log, "WebBrowser.Capture.Page")
10 : QObject{parent}
11{}
12
13void CCaptureFullPage::Start(QWebEngineView *view, QUrl url, QString szFile)
14{
15 if(!view || url.isEmpty() || szFile.isEmpty())
16 return;
17 m_szFile = szFile;
18 m_view = view;
19 stepInit();
20}
21
22void CCaptureFullPage::stepInit()
23{
24 qDebug(log) << "contents size:" << m_view->page()->contentsSize();
25 // 获取页面总高度
26 m_totalHeight = m_view->page()->contentsSize().height();
27 m_viewportHeight = m_view->size().height();
28 m_deltaY = m_viewportHeight;
29 m_currentY = 0;
30 m_images.clear();
31 m_view->page()->runJavaScript(
32 "document.documentElement.scrollTop;",
33 [this](const QVariant &result) {
34 m_originY = result.toInt();
35 //qDebug(log) << "OriginY:" << m_originY;
36 });
37 stepScroll();
38}
39
40void CCaptureFullPage::stepScroll()
41{
42 if (m_currentY >= m_totalHeight) {
43 composeImage();
44 return;
45 }
46
47 // 滚动到当前位置
48 m_view->page()->runJavaScript(
49 QString("window.scrollTo(0, %1);").arg(m_currentY),
50 [this](const QVariant &) {
51 // 等待渲染
52 QTimer::singleShot(500, this, &CCaptureFullPage::stepGrab);
53 }
54 );
55}
56
57void CCaptureFullPage::stepGrab()
58{
59 QImage img = m_view->grab().toImage();
60 // 如果是最后一块,有可能要裁掉多余的部分
61 int expectedHeight = (m_currentY + m_deltaY > m_totalHeight) ? (m_totalHeight - m_currentY) : m_deltaY;
62 if (img.height() > expectedHeight) {
63 img = img.copy(0, 0, img.width(), expectedHeight);
64 }
65
66 m_images.append(img);
67 m_currentY += m_deltaY;
68 stepScroll(); // 进入下一分块
69}
70
71void CCaptureFullPage::composeImage()
72{
73 if (!m_images.isEmpty()) {
74 int fullWidth = m_images[0].width();
75 int fullHeight = 0;
76 foreach (const QImage &img, m_images) fullHeight += img.height();
77
78 QImage result(fullWidth, fullHeight, m_images[0].format());
79 QPainter painter(&result);
80 int y = 0;
81 foreach (const QImage &img, m_images) {
82 painter.drawImage(0, y, img);
83 y += img.height();
84 }
85 painter.end();
86 result.save(m_szFile);
87 qDebug() << "Full page screenshot saved to" << m_szFile;
88 }
89 m_view->page()->runJavaScript(
90 QString("window.scrollTo(0, %1);").arg(m_originY),
91 [this](const QVariant &) {});
92 emit sigFinished();
93}