Сохранение изображения в файл png

Я хочу сохранить веб-страницу в файл png с помощью javascript. Мне надоел приведенный ниже пример кода. но в чем проблема, когда я загружаю, это расширение загрузки image/octet-stream, но во время загрузки файла я хочу сохранить изображение в формате png. Как я могу загрузить изображение из расширения image / octet-stream в расширение png. код:

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>html2canvas example</title>
 <script type="text/javascript" src="js/html2canvas.js"></script>
  <script type="text/javascript" src="js/excanvas.js"></script>

    <style>
    canvas{border:1px solid #222}
    </style>
</head>
<body id="target">
      <a class="upload"  >Upload to Imgur</a>  
    <a href="#" download="testXXX.jpg" onclick="printImg()" ><img src="images/print-icon.png" alt="Print" width="16" height="16" ></a>
    <h2>this is <b>bold</b> <span style="color:red">red</span></h2>   
    <p> Feedback form with screenshot This script allows you to create feedback forms which include a screenshot, 
    created on the clients browser, along with the form. 
    The screenshot is based on the DOM and as such may not be 100% accurate to the real 
    representation as it does not make an actual screenshot, but builds the screenshot based on the 
    information available on the page. How does it work? The script is based on the html2canvas library,
     which renders the current page as a canvas image, by reading the DOM and the different styles applied 
     to the elements. This script adds the options for the user to draw elements on top of that image, 
     such as mark points of interest on the image along with the feedback they send.
      It does not require any rendering from the server, as the whole image is created on the clients browser.
       No plugins, no flash, no interaction needed from the server, just pure JavaScript! Browser compatibility Firefox 3.5+ Newer versions of Google Chrome, Safari & Opera IE9
    </p>


    <script type="text/javascript">

    function printImg(){
        html2canvas( [ document.body ],{
          onrendered: function(canvas) {

          var img = canvas.toDataURL("image/png").replace("image/png","image/octet-stream;base64");                 
          window.location.href=img;

          }
        });
      }


    </script> 
</body>
</html>

person Navyah    schedule 10.10.2013    source источник


Ответы (1)


Боюсь, что именно так работает toDataURL.

См. Следующий вопрос для ответа с несколько уродливым решением:

Назовите файл PNG, сохраненный с Canvas, используя открыть диалоговое окно с помощью

(href в ответе будет указывать на var img в вашем javascript)

person madeddie    schedule 10.10.2013
comment
Мне нужно загрузить его в мою локальную систему, по приведенной выше ссылке, которую вы опубликовали, говорится, что нужно загрузить его на сервер - person Navyah; 10.10.2013
comment
Я не уверен, что вы имеете в виду, выбранный ответ создает ссылку, при нажатии которой ваш браузер загружает изображение. Однако главное заключается в том, что не всегда (для всех браузеров) можно загрузить снимок экрана с помощью только функции Canvas toDataUrl. - person madeddie; 11.10.2013
comment
Привет, madeddie, есть ли другой подход на стороне клиента, где мы можем сделать снимок экрана и сохранить его в файле png - person Navyah; 11.10.2013
comment
Не совсем, зачем тебе это нужно? Возможно, мы сможем придумать другое решение. - person madeddie; 11.10.2013
comment
Что именно мне нужно, так это в моем приложении я хочу сохранить кнопку печати, когда пользователь нажимает кнопку печати, ему необходимо сделать снимок экрана моего приложения и сохранить его в файле png. - person Navyah; 11.10.2013
comment
Это не почему, а что :) Почему это должно быть на стороне клиента? Не могли бы вы отрендерить страницу через PHP или что-то еще и таким образом сгенерировать png? - person madeddie; 11.10.2013
comment
Я не знаю php, могу попробовать с jsp, html и javascript - person Navyah; 11.10.2013