export const imageToBase64 = async (file: any) => { const reader = new FileReader(); reader.readAsDataURL(file); // 文件转base64 return new Promise(function (resolve) { reader.addEventListener("load", (e) => { // callback && callback(e.target.result); resolve(e); }) }); }; export const compress = (originalImage: any, compressRatio = 1) => { const image = new Image(); image.src = originalImage; // document.body.appendChild(image); // 原图预览 return new Promise(function (resolve) { /* 监听图片的load事件 */ image.addEventListener("load", function () { let [sizeRatio, maxWidth, maxHeight] = [0, 1024, 1024]; // 图片压缩宽高比例和最大宽高 let [imageWidth, imageHeight] = [this.naturalWidth, this.naturalHeight]; // 图片实际宽高 let compressFlag = false; // 图片是否需要压缩 // 如果图片宽度大于最大宽度就等比压缩图片的高度 if (imageWidth > maxWidth) { compressFlag = true; sizeRatio = imageWidth / maxWidth; maxHeight = imageHeight / sizeRatio; } // 如果图片高度大于最大高度就等比压缩图片的宽度 if (imageHeight > maxHeight) { compressFlag = true; sizeRatio = imageHeight / maxHeight; maxWidth = imageWidth / sizeRatio; } // 如果不需要压缩 if (!compressFlag) { maxWidth = imageWidth; maxHeight = imageHeight; } // 使用canvas压缩图片 const canvas = document.createElement("canvas"); const ctx: any = canvas.getContext("2d"); canvas.setAttribute("id", "canvas"); canvas.width = maxWidth; canvas.height = maxHeight; // document.body.appendChild(canvas); // canvas预览 ctx.clearRect(0, 0, maxWidth, maxHeight); // 清除画布内所有像素 ctx.drawImage(image, 0, 0, maxWidth, maxHeight); // canvas绘制当前图片 const compressImage = canvas.toDataURL("image/jpeg", compressRatio); // 设置压缩类型和压缩比例获取压缩后的文件 resolve(compressImage) }); }) } export const dataURLtoBlob = (dataurl: any) => { let arr = dataurl.split(',') let mime = arr[0].match(/:(.*?);/)[1] let bstr = atob(arr[1]) let n = bstr.length let u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); } export const blobToFile = (theBlob: any, fileName: any) => { theBlob.lastModifiedDate = new Date(); // 文件最后的修改日期 theBlob.name = fileName; // 文件名 return new File([theBlob], fileName, { type: theBlob.type, lastModified: Date.now() }); }