摘自:https://www.cnblogs.com/jyuf/p/7251591.html 函數都比較簡單,直接看就ok了 ...
摘自:https://www.cnblogs.com/jyuf/p/7251591.html
函數都比較簡單,直接看就ok了
/*-----------------------------------------------------------------------*/ // canvas轉dataURL:canvas對象、轉換格式、圖像品質 function canvasToDataURL(canvas, format, quality){ return canvas.toDataURL(format||'image/jpeg', quality||1.0); } // DataURL轉canvas function dataURLToCanvas(dataurl, cb){ var canvas = document.createElement('CANVAS'); var ctx = canvas.getContext('2d'); var img = new Image(); img.onload = function(){ canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0); cb(canvas); }; img.src = dataurl; } /*-----------------------------------------------------------------------*/ // image轉canvas:圖片地址 function imageToCanvas(src, cb){ var canvas = document.createElement('CANVAS'); var ctx = canvas.getContext('2d'); var img = new Image(); img.src = src; img.onload = function (){ canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0); cb(canvas); }; } // canvas轉image function canvasToImage(canvas){ var img = new Image(); img.src = canvas.toDataURL('image/jpeg', 1.0); return img; } /*-----------------------------------------------------------------------*/ // File/Blob對象轉DataURL function fileOrBlobToDataURL(obj, cb){ var a = new FileReader(); a.readAsDataURL(obj); a.onload = function (e){ cb(e.target.result); }; } // DataURL轉Blob對象 function dataURLToBlob(dataurl){ var arr = dataurl.split(','); var mime = arr[0].match(/:(.*?);/)[1]; var bstr = atob(arr[1]); var n = bstr.length; var u8arr = new Uint8Array(n); while(n--){ u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], {type:mime}); } /*-----------------------------------------------------------------------*/ // Blob轉image function blobToImage(blob, cb){ fileOrBlobToDataURL(blob, function (dataurl){ var img = new Image(); img.src = dataurl; cb(img); }); } // image轉Blob function imageToBlob(src, cb){ imageToCanvas(src, function (canvas){ cb(dataURLToBlob(canvasToDataURL(canvas))); }); } /*-----------------------------------------------------------------------*/ // Blob轉canvas function BlobToCanvas(blob, cb){ fileOrBlobToDataURL(blob, function (dataurl){ dataURLToCanvas(dataurl, cb); }); } // canvas轉Blob function canvasToBlob(canvas, cb){ cb(dataURLToBlob(canvasToDataURL(canvas))); } /*-----------------------------------------------------------------------*/ // image轉dataURL function imageToDataURL(src, cb){ imageToCanvas(src, function (canvas){ cb(canvasToDataURL(canvas)); }); } // dataURL轉image,這個不需要轉,直接給了src就能用 function dataURLToImage(dataurl){ var img = new Image(); img.src = d; return img; } /*-----------------------------------------------------------------------*/