canvas转img,blob相互转换
程序员文章站
2022-07-06 07:53:08
摘自: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; } /*-----------------------------------------------------------------------*/