Convert HTML5 Canvas into File to be uploaded?

后端 未结 5 1681
生来不讨喜
生来不讨喜 2020-11-28 03:54

The standard HTML file upload works as follows:



        
5条回答
  •  佛祖请我去吃肉
    2020-11-28 04:29

    The canvas image needs to be converted to base64 and then from base64 in to binary. This is done using .toDataURL() and dataURItoBlob()

    It was a pretty fiddly process which required piecing together several SO answers, various blog posts and tutorials.

    I've created a tutorial you can follow which walks you through the process.

    In response to Ateik's comment here's a fiddle which replicates the original post in case you're having trouble viewing the original link. You can also fork my project here.

    There's a lot of code but the core of what I'm doing is take a canvas element:

    
    

    Set it's context to 2D

    var snap = document.getElementById('flatten');
    var flatten = snap.getContext('2d');
    

    Canvas => Base64 => Binary

    function postCanvasToURL() {
      // Convert canvas image to Base64
      var img = snap.toDataURL();
      // Convert Base64 image to binary
      var file = dataURItoBlob(img);
    }
    
    function dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);
    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ia], {type:mimeString});
    }

    You could stop at base64 if that's all you need, in my case I needed to convert again to binary so that I could pass the data over to twitter (using OAuth) without use of a db. It turns out you can tweet binary which is pretty cool, twitter will convert it back in to an image.

提交回复
热议问题