How to save an HTML5 Canvas as an image on a server?

后端 未结 8 2219
走了就别回头了
走了就别回头了 2020-11-21 23:50

I\'m working on a generative art project where I would like to allow users to save the resulting images from an algorithm. The general idea is:

  • Create an image
8条回答
  •  一向
    一向 (楼主)
    2020-11-22 00:31

    I've worked on something similar. Had to convert canvas Base64-encoded image to Uint8Array Blob.

    function b64ToUint8Array(b64Image) {
       var img = atob(b64Image.split(',')[1]);
       var img_buffer = [];
       var i = 0;
       while (i < img.length) {
          img_buffer.push(img.charCodeAt(i));
          i++;
       }
       return new Uint8Array(img_buffer);
    }
    
    var b64Image = canvas.toDataURL('image/jpeg');
    var u8Image  = b64ToUint8Array(b64Image);
    
    var formData = new FormData();
    formData.append("image", new Blob([ u8Image ], {type: "image/jpg"}));
    
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/api/upload", true);
    xhr.send(formData);
    

提交回复
热议问题