1.图片路径转64
function imageUrlToBase64(url) {
let homeImage = new Image();
// 解决跨域问题
homeImage.setAttribute("crossOrigin", "anonymous");
homeImage.src = url;
//homeImage.onload为异步加载
homeImage.onload = () => {
let canvas = document.createElement("canvas");
canvas.width = homeImage.width;
canvas.height = homeImage.height;
let context = canvas.getContext("2d");
context.drawImage(homeImage, 0, 0, homeImage.width, homeImage.height);
let quality = 0.8;
// 这里的dataurl就是base64类型
let dataURL = canvas.toDataURL("image/jpeg", quality);
console.log(dataURL);
// base64ToFile(dataURL, "moren"); // 这里是将base64转为file格式的方法
};
}
1.1图片转file
function imageToBase64(homeImage) {
let canvas = document.createElement("canvas");
canvas.width = homeImage.width;
canvas.height = homeImage.height;
let ctx = canvas.getContext("2d");
ctx.drawImage(homeImage, 0, 0, homeImage.width, homeImage.height);
let ext = img.src.substring(homeImage.src.lastIndexOf(".") + 1).toLowerCase();
let dataURL = canvas.toDataURL("image/jpeg" + ext);
console.log(dataURL);
return dataURL;
};
2.base64转file
function base64ToFile(base64, fileName) {
let arr = base64.split(",");
let mime = arr[0].match(/:(.*?);/)[1];
let bytes = atob(arr[1]);
let n = bytes.length;
let ia = new Uint8Array(n);
while (n--) {
ia[n] = bytes.charCodeAt(n);
}
return new File([ia], fileName, { type: mime }); // 将值抛出去
}
3.file转base64
function getBase64(file) {
// 直接将处理结果返回
return new Promise((resolve, reject) => {
let reader = new FileReader();
let fileResult = "";
reader.readAsDataURL(file);
reader.onload = () => {
fileResult = reader.result.toString();
};
reader.onerror = (error) => {
reject(error);
};
reader.onloadend = () => {
resolve(fileResult);
};
});
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)