1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- /**
- * @param {file}
- * @returns {string} 转Base64文件
- */
- export function getBase64(file:any) {
- return new Promise((resolve, reject) => {
- ///FileReader类就是专门⽤来读⽂件的
- const reader = new FileReader();
- //开始读⽂件
- //readAsDataURL: dataurl它的本质就是图⽚的⼆进制数据,进⾏base64加密后形成的⼀个字符串,
- reader.readAsDataURL(file);
- // 成功和失败返回对应的信息,reader.result⼀个base64,可以直接使⽤
- reader.onload = () => resolve(reader.result);
- // 失败返回失败的信息
- reader.onerror = (error) => reject(error);
- });
- }
- /**
- * @param {base64url}
- * @returns {string} // 获取文件得大小
- */
- export function calSize(base64url:string) {
- let str = base64url.replace('data:image/png;base64,', '');
- const equalIndex = str.indexOf('=');
- if(str.indexOf('=') > 0) {
- str = str.substring(0, equalIndex);
- }
- const strLength = str.length;
- const fileLength = strLength - (strLength / 8) * 2;
- // 返回单位为MB的大小
- return parseFloat((fileLength / (1024 * 1024)).toFixed(2));
- }
- /**
- * @param {path,w,callback}
- * @returns {callback} // 通过canvas压缩base64图片 并压缩
- */
- export function dealImage(path:string, w=1000, callback:any){
- const newImage = new Image();
- const size=calSize(path);//获取mb大小
- let quality = 0.52
- if(size<=1){//1 mb
- quality=0.9;
- }
- if(size>1){
- quality = 0.8
- }
- newImage.src = path;
- newImage.setAttribute("crossOrigin", 'Anonymous'); // url为外域时需要
- let imgWidth;
- let imgHeight;
- newImage.onload = function() {
- imgWidth = newImage.width;
- imgHeight = newImage.height;
- const canvas = document.createElement("canvas");
- const ctx = canvas.getContext("2d") as any;
- if (Math.max(imgWidth, imgHeight) > w) {
- if (imgWidth > imgHeight) {
- canvas.width = w;
- canvas.height = w * imgHeight / imgWidth;
- } else {
- canvas.height = w;
- canvas.width = w * imgWidth / imgHeight;
- }
- } else {
- canvas.width = imgWidth;
- canvas.height = imgHeight;
- }
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- ctx.drawImage(newImage, 0, 0, canvas.width, canvas.height);
- const newBase64 = canvas.toDataURL("image/jpeg", quality);
- callback(newBase64);
- }
- }
- /**
- * 统一批量导出
- * @method getBase64 文件转base64
- * @method dealImage 压缩图片
- * @method calSize 获取图片大小
- */
- const other = {
- base64: (file:any) => {
- return getBase64(file)
- },
- getDealImage:(path:any, w:number, callback:any)=>{
- return dealImage(path, w, callback)
- },
- getCalSize:(url:string)=>{
- return calSize(url)
- }
- }
|