使用canvas压缩图片,图片不容易失真变形。
1.首先在js文件写入
/** 图片压缩,默认同比例压缩
* @param {Object} fileObj
* 图片对象
* 回调函数有一个参数,base64的字符串数据
*/
export function compress(fileObj, callback) {
try {
const image = new Image()
image.src = URL.createObjectURL(fileObj)
image.onload = function () {
const that = this
// 默认按比例压缩
let w = that.width
let h = that.height
const scale = w / h
w = fileObj.width || w
h = fileObj.height || (w / scale)
let quality = 0.7 // 默认图片质量为0.7
// 生成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)
ctx.drawImage(that, 0, 0, w, h)
// 图像质量
if (fileObj.quality && fileObj.quality <= 1 && fileObj.quality > 0) {
quality = fileObj.quality
}
// quality值越小,所绘制出的图像越模糊
const data = canvas.toDataURL('image/jpeg', quality)
// 压缩完成执行回调
const newFile = convertBase64UrlToBlob(data)
callback(newFile)
}
} catch (e) {
}
}
2.在自定义公共组件Global.vue中引入创建全局变量
<script>
import { getToken } from "@/utils/auth";
import { compress } from "@/utils/index";
const fileUrl = "";
const token = getToken();
const myHeaders = { token: token };
export default {
fileUrl, //附件地址
myHeaders, //element-ui上传带token
compress //压缩图片函数
};
</script>
3.在main.js,注册全局文件
// 定义全局 变量
import global_ from '@/components/Global/Global.vue'//引用文件
Vue.prototype.GLOBAL = global_//挂载到Vue实例上面
4.在文件中使用
fileChangePlans(file, fileList) {
this.$refs.uploadPrice.clearFiles();
let _this = this;
let obj = {
imgUrl: "",
name: ""
};
const testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
const isJpgOrPng =
testmsg === "jpg" ||
testmsg === "JPG" ||
testmsg === "png" ||
testmsg === "PNG" ||
testmsg === "GIF" ||
testmsg === "gif";
let fileListData = [];
for (let x = 0; x < fileList.length; x++) {
let item1 = fileList[x];
if (isJpgOrPng) {
// 图片才压缩
this.GLOBAL.compress(item1.raw, async function(val) {
let newfile = new window.File([val], file.name, {
type: file.type
});
newfile.uid = file.uid;
fileListData.push(newfile);
const formData = new FormData();
formData.append(`img`, fileListData[0]);
await img(formData).then(res => {
_this.$set(_this.dailyFinishFiles, "imgUrl", res.data.data);
});
setTimeout(() => {
_this.stats = true;
}, 100);
});
var file = item1.raw;
obj.name = item1.name;
var reader = new FileReader();
reader.onload = function(e) {
// 转base64
obj.imgUrl = e.target.result;
};
reader.readAsDataURL(file);
} else {
this.$message({
showClose: true,
message: "请上传图片",
type: "error"
});
}
}
},