简体   繁体   English

如何在本地驱动器中保存网页屏幕截图

[英]How to save web page screenshot in local drive

I am working on a project and one of it's requirement is to take screenshot of web page and store that as an Image in local drive. 我正在从事一个项目,其中一项要求是获取网页的屏幕截图并将其作为图像存储在本地驱动器中。

I gone through a blog and got how can we take screenshot using JavaScript. 我浏览了一个博客 ,了解了如何使用JavaScript截屏。 I am able to get screenshot but how to save that as an Image in local drive ? 我可以获取屏幕截图,但是如何将其另存为本地驱动器中的图像?

My JQuery Code: 我的JQuery代码:

(function (exports) {
function urlsToAbsolute(nodeList) {
    if (!nodeList.length) {
        return [];
    }
    var attrName = 'href';
    if (nodeList[0].__proto__ === HTMLImageElement.prototype 
    || nodeList[0].__proto__ === HTMLScriptElement.prototype) {
        attrName = 'src';
    }
    nodeList = [].map.call(nodeList, function (el, i) {
        var attr = el.getAttribute(attrName);
        if (!attr) {
            return;
        }
        var absURL = /^(https?|data):/i.test(attr);
        if (absURL) {
            return el;
        } else {
            return el;
        }
    });
    return nodeList;
}

function screenshotPage() {
    urlsToAbsolute(document.images);
    urlsToAbsolute(document.querySelectorAll("link[rel='stylesheet']"));
    var screenshot = document.documentElement.cloneNode(true);
    var b = document.createElement('base');
    b.href = document.location.protocol + '//' + location.host;
    var head = screenshot.querySelector('head');
    head.insertBefore(b, head.firstChild);
    screenshot.style.pointerEvents = 'none';
    screenshot.style.overflow = 'hidden';
    screenshot.style.webkitUserSelect = 'none';
    screenshot.style.mozUserSelect = 'none';
    screenshot.style.msUserSelect = 'none';
    screenshot.style.oUserSelect = 'none';
    screenshot.style.userSelect = 'none';
    screenshot.dataset.scrollX = window.scrollX;
    screenshot.dataset.scrollY = window.scrollY;
    var script = document.createElement('script');
    script.textContent = '(' + addOnPageLoad_.toString() + ')();';
    screenshot.querySelector('body').appendChild(script);
    var blob = new Blob([screenshot.outerHTML], {
        type: 'text/html'
    });
    return blob;
}

function addOnPageLoad_() {
    window.addEventListener('DOMContentLoaded', function (e) {
        var scrollX = document.documentElement.dataset.scrollX || 0;
        var scrollY = document.documentElement.dataset.scrollY || 0;
        window.scrollTo(scrollX, scrollY);
    });
}

function generate() {
    window.URL = window.URL || window.webkitURL;
    window.open(window.URL.createObjectURL(screenshotPage()));
}
exports.screenshotPage = screenshotPage;
exports.generate = generate;
})(window);

This is my Fiddle 这是我的小提琴

As shown in my fiddle, I want to provide a button/link to user so that user can take snapshot of current window/web page. 如我的小提琴所示,我想向用户提供一个按钮/链接,以便用户可以获取当前窗口/网页的快照。 And able to download/save that snapshot as an image (png, jpeg, jpg any format). 并能够将该快照下载/保存为图像(png,jpeg,jpg等任何格式)。

You can't access the file system of the client directly. 您不能直接访问客户端的文件系统。 However, you can prompt them to download a file. 但是,您可以提示他们下载文件。

Data URLs 资料网址

Data URLs are URLs where the link contains the contents of a file. 数据URL是链接包含文件内容的URL。 For example: 例如:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAioAAAO0CAYAAACLKx00

That URL is cropped, so won't actually work. 该网址已被裁剪,因此实际上将无法使用。

Here is a fiddle: http://jsfiddle.net/x876K/6/ 这是一个小提琴: http : //jsfiddle.net/x876K/6/

You can force it to be downloaded by using a link like this: 您可以使用以下链接来强制下载:

<a download="file.png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAioAAAO0CAYAAACLKx00">text</a>

Try reading: 尝试阅读:

Please tell me if I have misunderstood. 如果我误会了,请告诉我。

Canvas and Image 画布和图像

You could also write to an canvas, and allow the user to right click and save as. 您也可以写到画布,并允许用户右键单击并另存为。

Here is my answer : 这是我的答案:

My index.php 我的index.php

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="js/html2canvas.js"></script>
<script type="text/javascript" src="js/jquery.plugin.html2canvas.js"></script>

<form method="POST" enctype="multipart/form-data" action="save.php" id="myForm">
<input type="hidden" name="img_val" id="img_val" value="" />
</form>

<input type="submit" value="Take Screenshot Of Div Below" onclick="capture();" />

<div id="target">
  DIV TO TAKE PHOTO OF.
</div>

<script>
function capture() {
    $('#target').html2canvas({
        onrendered: function (canvas) {
            //Set hidden field's value to image data (base-64 string)
            $('#img_val').val(canvas.toDataURL("image/png"));
            //Submit the form manually
            document.getElementById("myForm").submit();
        }
    });
}
</script>

My save.php 我的save.php

<?php
//Get the base-64 string from data
$filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);

//Decode the string
$unencodedData=base64_decode($filteredData);

//Save the image
file_put_contents('img.png', $unencodedData);

$file = 'img.png';

if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}

?>

This solution I found at a blog . 我在博客上找到这个解决方案。

Live Demo 现场演示

An example from https://retifrav.github.io/blog/2018/07/23/html-js-screenshot/ 来自https://retifrav.github.io/blog/2018/07/23/html-js-screenshot/的示例

<head>
  <script src="html2canvas.min.js"></script>
</head>
<div>
    <a id="a-make" href="#">Make a screenshot</a>
    <a id="a-download" href="#" style="display:none;">Download a screenshot</a>
</div>

<div id="main">
    <div id="screenshot">
        ...
    </div>
</div>

<script>
    function makeScreenshot()
    {
        html2canvas(document.getElementById("screenshot"), {scale: 2}).then(canvas =>
        {
            canvas.id = "canvasID";
            var main = document.getElementById("main");
            while (main.firstChild) { main.removeChild(main.firstChild); }
            main.appendChild(canvas);
        });
    }

    document.getElementById("a-make").addEventListener('click', function()
    {
        document.getElementById("a-make").style.display = "none";
        makeScreenshot();
        document.getElementById("a-download").style.display = "inline";
    }, false);

    document.getElementById("a-download").addEventListener('click', function()
    {
        this.href = document.getElementById("canvasID").toDataURL();
        this.download = "canvas-image.png";
    }, false);
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM