-
- export const compressImgNew = (file) => {
- return new Promise(resolve => {
- const reader = new FileReader()
- const image = new Image()
- image.onload = (imageEvent) => {
- const canvas = document.createElement('canvas') // 创建画布
- const context = canvas.getContext('2d') // 画布为2d
- // const width = image.width / 1.05 // 图片宽度 / 压缩比例
- // const height = image.height / 1.05 // 图片高度 / 压缩比例
- const width = image.width / 3 // 图片宽度 / 压缩比例
- const height = image.height / 3 // 图片高度 / 压缩比例
- canvas.width = width // 画布宽度
- canvas.height = height // 画布宽度
- context.clearRect(0, 0, width, height)
- context.drawImage(image, 0, 0, width, height)
- const dataUrl = canvas.toDataURL(file.type) //图片转路径
- const blobData = dataURLtoBlob(dataUrl, file.type) //图片转二进制
- resolve(blobData)
- }
- reader.onload = e => { image.src = e.target.result }
- reader.readAsDataURL(file)
- })
- };
-
- //图片转二进制
- function dataURLtoBlob(dataURL, type) {
- var binary = atob(dataURL.split(',')[1])
- var array = []
- for (var i = 0; i < binary.length; i++) {
- array.push(binary.charCodeAt(i))
- }
- return new Blob([new Uint8Array(array)], { type: type })
- }
-

import { compressImgNew } from “@/assets/js/picture.js”;
- beforeAvatarUpload(file) {
- let types = [
- "image/jpeg",
- "image/jpg",
- "image/png"
- ];
- const isImage = types.includes(file.type);
- const isLtSize = file.size / 1024 / 1024 < 5;
- if (!isImage) {
- this.$message.warning("上传图片只能是 JPG、JPEG、PNG 格式!");
- return false;
- }
- if (!isLtSize) {
- this.$message.warning("上传图片大小不能超过 5MB!");
- return false;
- }
- return compressImgNew(file);
- },