27

HTML5 Canvas转化成图片后上传服务器

 4 years ago
source link: https://www.tuicool.com/articles/maUZJju
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
UVZzEbn.jpg!web
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);

用上面这种方式在前端通过js处理,server端不需要进行任何额外处理。

我认为是最方便最直接的办法,反而很多高赞回复,需要server进行各种处理,不推荐。

Had to convert canvas Base64-encoded image to  Uint8Array Blob .

参考: https://stackoverflow.com/questions/13198131/how-to-save-an-html5-canvas-as-an-image-on-a-server


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK