1、解析一个项目,a标签的src文件地址,你如果直接去request,会发现返回的是一个二进制文件 �PNG =>例如这样的
百度了文章全是巴拉巴拉的,直接解决:
ajax增加属性: xhrFields: { responseType: “arraybuffer” },
var binary = "";
var bytes = new Uint8Array(result);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
console.log();
that.imgSrc = "data:img/png;base64," + window.btoa(binary);
我的就可以了
虽然网上巴拉巴拉的,但记录一下,万一以后用到呢,嘿嘿
图片转base64
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
var dataURL = canvas.toDataURL("image/" + ext);
return dataURL;
}
(() => {
let img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = 'http://666.itshare.club/1603509156777';
img.onload = () => {
let getBase64Str = getBase64Image(img);
}
})()
base64转二进制流
function dataURLtoBlob(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 u8arr
}
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
var dataURL = canvas.toDataURL("image/" + ext);
return dataURL;
}
(() => {
let img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = 'http://666.itshare.club/1603509156777';
img.onload = () => {
let getBase64Str = getBase64Image(img);
let getBlobStr = dataURLtoBlob(getBase64Str)
}
})()
使用atob()函数用于解码使用 base-64 编码的字符串 将二进制流转成图片 算了,偷点懒偷点懒
前端上传图片 base64转二进制上传
var dataURItoBlob = function (dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], {type: mimeString});
},
var fd = new FormData(),
var fname = (new Date().getTime()) + parseInt(Math.random() * 1000, 10) + ".jpg",
var blob = dataURItoBlob("data:image/jpg;base64," + that.imgEditerPlugin.encodeBase64());
fd.append("file", blob, fname);
$.ajax({
contentType: false,
cache: false,
url: uploadUrl,
type: "POST",
processData: false,
data: fd
}).then(function(){
);
|