Files
aida_front/src/tool/domTurnImg.js
X1627315083 e4b3ebe88b 合并代码
2024-08-19 10:36:46 +08:00

59 lines
1.8 KiB
JavaScript

import html2canvas from "html2canvas";
const getJpeg = dom =>{
return new Promise(resolve =>{
setTimeout(() => {
html2canvas(dom,{useCORS: true,}).then(canvas =>{
let base64 = canvas.toDataURL('image/jpeg',.9);
// let quality = 0.9 // 压缩系数0-1之间
let newImage = new Image()
newImage.src = base64
newImage.setAttribute('crossOrigin', 'Anonymous') // url为外域时需要
const filename = new Date().toISOString() + '.jpg';
resolve(base64ToFile(base64,filename))
newImage.remove()
// }
})
}, 100);
})
}
function base64ToFile(base64,filename) {
// 从 Base64 编码中去掉数据类型描述部分
const base64Str = base64.replace(/^data:image\/[a-z]+;base64,/, '');
// 解码 Base64 字符串
const byteCharacters = atob(base64Str);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
// 创建 File 对象
const file = new File([byteArray], filename, { type: 'image/jpeg' }); // 根据需要的类型进行修改
console.log(file);
return file;
}
//base64转成blob
function dataURLtoFile(dataURI, type) {
let binary = atob(dataURI.split(",")[1]);
let array = [];
for (let i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], { type: "image/jpeg" });
}
//转换
// const base64ToFile = urlData =>{
// const arr = urlData.split(',');
// const mime = arr[0].match(/:(.*?);/)[1]
// const bytes = atob(arr[1])
// let n = bytes.length;
// const ia = new Uint8Array(n)
// while (n--){
// ia[n] = bytes.charCodeAt(n);
// }
// return new File([ia],'jpeg',{type:mime})
// }
export default getJpeg