Javascript and dataurlblob that are mutually converted between DataURL and File, Blob, and canvas objects
Convert canvas to dataURL (get dataURL from canvas)
var dataurl = canvas.toDataURL('image/png');
Convert File objects to dataURL and Blob objects to dataURL
The File object is also a Blob object, and the processing is the same.
function readBlobAsDataURL(blob, callback) { var a = new FileReader(); a.onload = function(e) {callback(e.target.result);}; a.readAsDataURL(blob);}//example:readBlobAsDataURL(blob, function (dataurl){ console.log(dataurl);});readBlobAsDataURL(file, function (dataurl){ console.log(dataurl);});
Convert dataURL to Blob Object
function dataURItoBlob(dataURI) { var arr = dataURI.split(','), mime = arr[0].match(/:(.*?);/)[1]; return new Blob([atob(arr[1])], {type:mime});}//test:var blob = dataURItoBlob('data:text/plain;base64,YWFhYWFhYQ==');
Draw dataURL image data to canvas
First construct the Image object, src is dataURL, and the Image is drawn to canvas after onload.
var img = new Image();img.onload = function(){ canvas.drawImage(img);};img.src = dataurl;
File, Blob image File data is drawn to canvas
Convert to a url first, and then construct the Image object. src is dataURL, and the Image is drawn to canvas after the onload.
The preceding readBlobAsDataURL function is used to obtain a url in dataURL format from a File or Blob Object. For more information, seeDraw dataURL image data to canvas
readBlobAsDataURL(file, function (dataurl){ var img = new Image(); img.onload = function(){ canvas.drawImage(img); }; img.src = dataurl;});
Different methods are used to construct different types of URLs (dataURL, objectURL (blobURL), and filesystemURL ). Here we will not describe them one by one. We only use dataURL as an example.
FilesystemURL is not a local file URL (file :///....), The format is similarfilesystem:http://...
Supports the browser support of the sandbox File System (currently only Chrome.
Convert Canvas to Blob Object and use Ajax to send
After converting to a Blob object, you can use Ajax to upload image files.
Get dataurl from canvas first, and then convert dataurl to Blob Object
Var dataurl = canvas. toDataURL ('image/png '); var blob = dataURItoBlob (dataurl); // use ajax to send var fd = new FormData (); fd. append ("image", blob, "image.png"); var xhr = new XMLHttpRequest (); xhr. open ('post', '/Server', true); xhr. send (fd );
Reprinted please keep source http://blog.csdn.net/cuixiping/article/details/45932793