How to save a canvas image with a specific filename

家住魔仙堡 提交于 2020-01-25 20:16:20

问题


I have a web page that can show a live stream and then be able to snap shot the live stream.

I need to have a button that can save the image in the canvas with a specific file name of my own (it can be the date for today).

Badly need it. Thanks to those who will respond! :)

Here's the code:

<!DOCTYPE html>
<html>
<head>
<title>Video Live Stream</title>
<link rel="stylesheet" type="text/css" href="demo'.css"/>
</head>
<body>
<center>
<style>
    <p>
    video { border: 20px solid #ccc; display: block; margin: 0 0 -5px 0; }
    #canvas { margin-top: 20px; border: 1px solid #ccc; display: block; }

    </p>
</style>
</br>
<h3>Live Stream with Snap Shot</h3>
<div align="center">
    <video style="position:relative;top:-75px;" id="video" width="600" height="600" autoplay="">
    </video>
</div>
<div align="center">
<button style="position:relative;top:-60px;" id="snap" class="sexyButton">Snap Photo</button>
<canvas style="position:relative;top:-60px;" class="input" id="canvas" width="640" height="480"></canvas>

</div>
<a href="#" id="downloader" onclick="$filename">Download!</a>
<script>

    // Put event listeners into place
    window.addEventListener("DOMContentLoaded", function() {
        // Grab elements, create settings, etc.
        var canvas = document.getElementById("canvas"),
            context = canvas.getContext("2d"),
            video = document.getElementById("video"),
            videoObj = { "video": true },
            errBack = function(error) {
                console.log("Video capture error: ", error.code); 
            };
        // Put video listeners into place
        if(navigator.getUserMedia) { // Standard
            navigator.getUserMedia(videoObj, function(stream) {
                video.src = stream;
                video.play();
            }, errBack);
        } else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
            navigator.webkitGetUserMedia(videoObj, function(stream){
                video.src = window.webkitURL.createObjectURL(stream);
                video.play();
            }, errBack);
        } else if(navigator.mozGetUserMedia) { // WebKit-prefixed
            navigator.mozGetUserMedia(videoObj, function(stream){
                video.src = window.URL.createObjectURL(stream);
                video.play();
            }, errBack);
        }
        // Trigger photo take
        document.getElementById("snap").addEventListener("click", function() {
            context.drawImage(video, 0, 0, 640, 480);
        });

    }, false);
</script>
</center>
</body>
</html>

回答1:


Automatic file Download

You can not guarantee a filename but you can suggest a filename. The client may override the filename as it is just a download request and subject to the clients download policies. Event if the user allows the file to save with the name given the browser may still change the name if the file exist in the download directory by appending to the filename (or other stuff depending on the browser).

Here is a simple download image function. It will attempt to save (via download) to the client's file system the image as a PNG with the given filename. Will take an image or canvas image.

Update

As pointed out by markE the download attribute that I use to set the filename is not supported on all browsers. So only browser that support the attribute will let you set the download name.

Further the function given will also not download if the MouseEvent object is not supported. I have added a legacy method fireEvent for older browsers namely IE otherwise the function will not download.

function saveAsPNG(image, filename){ // No IE <11 support. Chrome URL bug for large images may crash
    var anchorElement, event, blob;
    function image2Canvas(image){  // converts an image to canvas
        function createCanvas(width, height){  // creates a canvas of width height
            var can = document.createElement("canvas");
            can.width = width;
            can.height = height;
            return can;
        };
        var newImage = canvas(img.width, img.height); // create new image
        newImage.ctx = newImage.getContext("2d");  // get image context
        newImage.ctx.drawImage(image, 0, 0); // draw the image onto the canvas
        return newImage;  // return the new image
    }
    if(image.toDataURL === undefined){    // does the image have the toDataURL function
        image = image2Canvas(image);  // No then convert to canvas
    }
    // if msToBlob and msSaveBlob then use them to save. IE >= 10
    // As suggested by Kaiido 
    if(image.msToBlob !== undefined && navigator.msSaveBlob !== undefined){ 
       blob = image.msToBlob(); 
       navigator.msSaveBlob(blob, filename + ".png"); 
       return;
    }
    anchorElement = document.createElement('a');  // Create a download link
    anchorElement.href = image.toDataURL();   // attach the image data URL
    // check for download attribute
    if ( anchorElement.download !== undefined ) {
        anchorElement.download = filename + ".png";  // set the download filename
        if (typeof MouseEvent === "function") {   // does the browser support the object MouseEvent
            event = new MouseEvent(   // yes create a new mouse click event
                "click", {
                    view        : window,
                    bubbles     : true,
                    cancelable  : true,
                    ctrlKey     : false,
                    altKey      : false,
                    shiftKey    : false,
                    metaKey     : false,
                    button      : 0,
                    buttons     : 1,
                }
            );
            anchorElement.dispatchEvent(event); // simulate a click on the download link.
        } else
        if (anchorElement.fireEvent) {    // if no MouseEvent object try fireEvent 
            anchorElement.fireEvent("onclick");
        }
    }
}

To use the function

saveAsPNG(canvas,"MyTest"); // Will attempt to save the canvas as "MyTest.png"

This does not guarantee that the file will be saved or that the filename will be what you want. If you want to guarantee a filename you must then save the file inside a zip file. This is a lot of work and still does not guarantee that the file will be saved. Security dictates that the client must have the right to accept or reject any download request. There is no way to side step this.




回答2:


I just found a way to save the canvas image with the filename of your own. You can find it at

http://eligrey.com/demos/FileSaver.js/

edit the canvas part:

<section id="image-demo">
 <form id="canvas-options">
 <label>Filename: <input type="text" class="filename" id="canvas-filename" placeholder="filename"/>.png</label>
        <input type="submit" value="Save"/>
        <input type="button" id="canvas-clear" value="Clear"/>
</form>

and insert the following scripts:

<script type="application/ecmascript" async="" src="Blob.js"/>
<script type="application/ecmascript" async="" src="canvas-toBlob.js"/>
<script type="application/ecmascript" async="" src="FileSaver.js"/>
<script type="application/ecmascript">

It worked!



来源:https://stackoverflow.com/questions/34704488/how-to-save-a-canvas-image-with-a-specific-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!