简体   繁体   English

canvas.toDataURL到img src

[英]canvas.toDataURL to img src

I recently downloaded an open source webcam to gif script and when the gif is created it saves as a dataurl. 我最近将一个开放源网络摄像头下载到gif脚本,当创建gif时,它另存为dataurl。 Is their a way I can change this? 他们可以改变我的方式吗? I would rather it save in a folder on the server and be something like http://example.com/folder/image.gif 我希望它保存在服务器上的文件夹中,并且类似http://example.com/folder/image.gif

Code: 码:

    *global GIFEncoder,encode64*/
var encoder = new GIFEncoder(),
    video = document.querySelector('video'),
    canvas = document.querySelector('canvas'),
    ctx = canvas.getContext('2d'),
    localMediaStream = null,
    snapshotPause = 0,
    recording = true,
    framesPause = 120,
    maxFrames = 28,
    totalFrames = 0,
    t;

encoder.setSize(320, 240);
encoder.setRepeat(0);
encoder.setDelay(framesPause);
encoder.setQuality(90);

window.URL = window.URL || window.webkitURL;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

if (navigator.getUserMedia) {
    navigator.getUserMedia({
            audio: true,
            video: true
        }, function (stream) {
            $('#start-image, #start-fake').hide();
            $('#video, #start').show();
            video.src = window.URL.createObjectURL(stream);
            localMediaStream = stream;
        }, function (e) {
            console.log('Error:', e);
        }
    );
} else {
    console.log('not supported');
}

function snapshot() {
    if (localMediaStream) {
        ctx.drawImage(video, 0, 0, 320, 240);
        encoder.addFrame(ctx);

        var image = $('<img />').attr('src', canvas.toDataURL('image/gif'));
        $('#thumbs').append(image);
        totalFrames++;
        if (totalFrames === maxFrames) {
            recordingEnd();
        }
    }
}

    function recordingEnd() {
    var binaryGif = encoder.stream().getData(),
        dataUrl = 'data:image/gif;base64,' + encode64(binaryGif),
        gif = $('<img />').attr('src', dataUrl);

    totalFrames = 0;
    recording = !recording;

    $('#start').html('Start');
    clearInterval(t);
    $('#indicator').hide();

    encoder.finish();

    $('#result-gif').html('').append(gif);
    overlayShow('preview');
    //b64 = encode64(binaryGif);
}

function overlayShow(panel) {
    $('.panel').hide();
    $('#' + panel).show();
    $('#overlay-bg').show();
    $('#overlay').show();
}

function overlayHide() {
    $('#overlay-bg').hide();
    $('#overlay').hide();
}

$('#start').click(function () {

    if (recording) {

        recording = !recording;

        $('#thumbs-holder-close').show();
        $('#thumbs-holder').animate({
            'margin-left': '320px'
        }, 300);
        $('#thumbs').html('');
        encoder.start();

        $('#indicator').show().animate({
            width: '100%'
        }, snapshotPause, function () {
            $('#indicator').css({
                'width': '0'
            });
        });

        t = setInterval(function () {

            snapshot();
            $('#indicator').animate({
                width: '100%'
            }, snapshotPause, function () {
                $('#indicator').css({
                    'width': '0'
                });
            });
        }, snapshotPause);

        $(this).html('Stop');

    } else {

        recordingEnd();
    }

});

    $('#thumbs-holder-close').click(function () {
    $(this).hide();
    $('#thumbs-holder').animate({
        'margin-left': 0
    }, 300);
});

$('#overlay-close').click(function () {
    overlayHide();
});

$('.new').click(function () {
    overlayHide();
});

$('#showSettings').click(function () {
    overlayShow('settings');
});

$('input[type=range]').change(function () {
    var id = $(this).attr('id'),
        val = $(this).val();
    $(this).next().html(val);
    window[id] = parseInt(val);
    if (id === 'framesPause') {
        framesPause = val;
        encoder.setDelay(framesPause);
    }
});

$('#save').click(function () {

     $.ajax({
         url: 'images/save.php',
         method: 'POST',
         data: {
             image: b64
         },
         dataType: 'json',
         success: function(data) {
             var a = $('<a />').attr('href', "images/" + data.name).html('permalink');
             $('#url').append(a);
         },
         error: function(err) {
             console.log(err);
         }
     });


 });

##Convert your dataUrl into Blobs ##将dataUrl转换为Blob

 
 
 
  
  function dataURLtoBlob(dataURL) { // Decode the dataURL var binary = atob(dataURL.split(',')[1]); // Create 8-bit unsigned array var array = []; for(var i = 0; i < binary.length; i++) { array.push(binary.charCodeAt(i)); } // Return our Blob object return new Blob([new Uint8Array(array)], {type: 'image/gif'}); } /* var file= dataURLtoBlob(dataURL); */
 
  

Now, you can add the Blob as FormData and send to server 现在,您可以将Blob添加为FormData并发送到服务器

Sending data as Blob instead of dataUrl. 将数据作为Blob而不是dataUrl发送。

As bergi pointed out, the encode.stream().getData() actually returns a binary string. 正如bergi指出的那样,encode.stream()。getData()实际上返回一个二进制字符串。

var array = [];
for(var i = 0; i < binaryGIF.length; i++) {
   array.push(binaryGIF.charCodeAt(i));
}
// Return our Blob object
var file = new Blob([new Uint8Array(array)], {type: 'image/gif'});

// Create new form data
var fd = new FormData();
// Append our Canvas image file to the form data
fd.append("sample-image-name-for-name-attribute", file);
// And send it
$.ajax({
   url: "my-rest-endpoint",
   type: "POST",
   data: fd,
   processData: false,
   contentType: false,
}).done(function(respond){
  alert(respond);
});

Hope it helps. 希望能帮助到你。 You should be able to use the file on the server as you handle a normal file upload. 处理正常的文件上传时,您应该能够使用服务器上的文件。

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

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