directTurnIntoBase64(fileObj, callback) { var r = new FileReader(); // 转成base64 r.onload = function() { //变成字符串 imgBase64 = r.result; console.log(imgBase64); callback(imgBase64); } r.readAsDataURL(fileObj); //转成Base64格式 }, compress(fileObj, callback) { var _this = this; if(typeof(FileReader) === 'undefined') { console.log("当前浏览器内核不支持base64图标压缩"); //调用上传方式不压缩 _this.directTurnIntoBase64(fileObj, callback); } else { try { var reader = new FileReader(); reader.onload = function(e) { var image = $('<img/>'); image.on('load', function() { var square = 700, //定义画布的大小,也就是图片压缩之后的像素 canvas = document.createElement('canvas'), context = canvas.getContext('2d'), imageWidth = 0, //压缩图片的大小 imageHeight = 0, offsetX = 0, offsetY = 0, data = ''; canvas.width = square; canvas.height = square; context.clearRect(0, 0, square, square); if(this.width > this.height) { imageWidth = square; imageHeight = square; offsetX = -Math.round((imageWidth - square) / 2); } else { imageHeight = square; imageWidth = square; offsetY = -Math.round((imageHeight - square) / 2); } context.drawImage(this, offsetX, offsetY, imageWidth, imageHeight); var data = canvas.toDataURL('image/jpeg'); //压缩完成执行回调 callback(data); }); image.attr('src', e.target.result); }; reader.readAsDataURL(fileObj); } catch(e) { console.log("压缩失败!"); //调用直接上传方式 不压缩 _this.directTurnIntoBase64(fileObj, callback); } } }, convertBase64UrlToBlob(urlData) { var bytes = window.atob(urlData.split(',')[1]); //去掉url的头,并转换为byte //处理异常,将ascii码小于0的转换为大于0 var ab = new ArrayBuffer(bytes.length); var ia = new Uint8Array(ab); for(var i = 0; i < bytes.length; i++) { ia[i] = bytes.charCodeAt(i); } return new Blob([ab], { type: 'image/png' }); },
以上就是主要代码,接下来引用:
fileChanged(e) {
var _this = this; const item = e.target.files[0];
_this.compress(item, function(imgBase64) { // console.log(imgBase64) if(item.size > 524288) { item = _this.convertBase64UrlToBlob(imgBase64); } if(item.size > 2097152) { alert("图片大小不能超过2M"); return; } _this.images =URL.createObjectURL(item); //压缩的图片进行回显
_this.files = item;
});
},
注意压缩后的图片赋值只能在回调里面进行赋值,如果写到外面会失效。
最后,图片上传给后台要加入到formData里面。
示例:
formData.append("photo", this.files, "file_" + Date.parse(new Date()) + ".png"); //存入
console.log(formData.getAll('photo')); //打印检查
这是使用js压缩图片,在哪都能用的,我是写vue项目时使用过。但其实vue是有相关的压缩图片的依赖的,具体可查看:https://blog.csdn.net/qq_34794264/article/details/80278243
很简单,看看就能用了,更方便点