js 压缩 预览 上传图片
com.js
export const compressImage=function (files,fn,preCallbackFn,i) {
let newfile = files.files[0];
let quality = 0.1;
const name = newfile.name; //文件名
let reader = new FileReader();
reader.readAsDataURL(newfile);
reader.onload = (e) => {
const src = e.target.result;
const img = new Image();
img.src = src;
img.onload = (e) => {
const w = img.width;
const h = img.height;
//生成canvas
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// 创建属性节点
const anw = document.createAttribute("width");
anw.nodeValue = w;
const anh = document.createAttribute("height");
anh.nodeValue = h;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
//铺底色 PNG转JPEG时透明区域会变黑色
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, w, h);
ctx.drawImage(img, 0, 0, w, h);
// quality值越小,所绘制出的图像越模糊
const base64 = canvas.toDataURL('image/jpeg', quality); //图片格式jpeg或webp可以选0-1质量区间
console.log(`原图${(src.length / 1024).toFixed(2)}kb`, `新图${(base64.length / 1024).toFixed(2)}kb`);
if(base64.length>1024*1024*1){
return false;
}
let arr = base64.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
let obj = new Blob([u8arr], {type:'image/jpeg'});
preCallbackFn && preCallbackFn(base64,obj,i);
fn && fn(obj);
}
}
};
//上传图片校验
export const checkImg=function(file){
var aa=file.value.toLowerCase().split('.');
if(!(aa[aa.length-1]=='gif'||aa[aa.length-1]=='jpg'||aa[aa.length-1]=='jpeg'||aa[aa.length-1]=='png')){
throw {code:400,msg:"请选择格式为*.jpg、*.gif、*.jpeg、*.png的图片"};
}
var imagSize = file.files[0].size;
if(imagSize>1024*1024*1){
throw {code:401,msg:"图片过大,无法上传"};
}
return true;
};
import {checkImg,compressImage} from "com";
imgPreview(){
let file=document.getElementById("imgInput");
try {
checkImg(file)
}catch(e) {
if(e.code==401){
if(compressImage(file,this.upImg,this.preCallbackFn) === false){
return alert(e.msg);
}
return true;
}else {
return alert(e.msg);
}
}
if (file.files && file.files[0]) {
let reader = new FileReader();
reader.onload = function (evt) {
let img = document.querySelector('#img_preview img');
img.setAttribute('src', evt.target.result);
}
reader.readAsDataURL(file.files[0]);
this.upImg(file.files[0]);
}
},
upImg(file){
let formData = new FormData();
formData.append("img", file,"image.jpeg");
//fileUpload 上传为接口
fileUpload(formData).then(data=>{
if(!data) return false;
userModifyImg(data).then(data=>{
if(!data) return false;
alert("上传图片成功!")
});
});
},