1.根据html元素获取图片base64 编码
var result = $('.cropper-example-1 > img').cropper("getCroppedCanvas");
var data = result.toDataURL();
2.base64 编码转二进制对象
Model.prototype.dataURLtoBlob = function(dataurl) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}
//调用
var blob = this.dataURLtoBlob(data);
3.二进制对象转base64 编码
Model.prototype.readBlobAsDataURL = function(blob, callback) {
var a = new FileReader();
a.onload = function(e) {
callback(e.target.result);
};
a.readAsDataURL(blob);
}
//调用
this.readBlobAsDataURL(blob, function (dataurl){
console.log(dataurl);
});
4.base64图片对象,画出图片:
Model.prototype.base64ForCanvas = function(data) {
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img = new Image();
img.onload = function(){
ctx.drawImage(img,0,0,200,200);
};
img.src = data;
}
//调用传base64数据
this.base64ForCanvas(data);
5.二进制或图片文件对象,页面显示
//Blob对象得到base64格式的url,再参考 base64图片数据绘制到canvas
Model.prototype.blobForCanvas = function(blob) {
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
this.readBlobAsDataURL(blob, function (dataurl){
var img = new Image();
img.onload = function(){
ctx.drawImage(img,0,0,200,200);
};
img.src = dataurl;
});
}
//调用传二进制数据
this.base64ForCanvas(blob);
6.imageData 转 blob
//imageData 转 blob
Model.prototype.button3Click = function(event){
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var imageData = ctx.getImageData(0,0,200,200);
var data = imageData.data;
var blob = new Blob([data]);
};
7.Blob to ArrayBuffer //Blob to ArrayBuffer
var reader = new FileReader();
reader.onload = function(e) {
callback(e.target.result);
};
reader.readAsArrayBuffer(blob);
类似文章介绍请参考:
https://www.cnblogs.com/flicat/p/5337054.html
https://www.cnblogs.com/tarol/p/5263050.html
评一波