|
| 1 | +/** |
| 2 | + * @param {file} 文件对象 |
| 3 | + * @param {imgType} 图片格式限制 |
| 4 | + * @param {size} 图片大小 |
| 5 | + * @param {width} 图片分辨率宽度 |
| 6 | + * @param {height} 图片分辨率高度 |
| 7 | + * @param {equalRation} 是否开启等比限制 |
| 8 | + */ |
| 9 | +export function checkImageFile(file, imgType = 'png', size = 1, width = 100, height = 100, equalRation = true ) { |
| 10 | + const isCorrectImgType = file.type === `image/${imgType}` |
| 11 | + const isLessThanSize = file.size / 1024 / 1024 < size |
| 12 | + if (!isCorrectImgType) { |
| 13 | + Message.error(`图片格式错误, 只能为${imgType}格式`) |
| 14 | + return false |
| 15 | + } else if (!isLessThanSize) { |
| 16 | + console.log(isLessThanSize) |
| 17 | + Message.error(`图片大小不能超过${size}MB`) |
| 18 | + return false |
| 19 | + } else { |
| 20 | + return new Promise((resolve, reject) => { |
| 21 | + const reader = new FileReader() |
| 22 | + reader.onload = function(e) { |
| 23 | + let image = new Image() |
| 24 | + image.onload = function() { |
| 25 | + let imgWidth = this.width |
| 26 | + let imgHeight = this.height |
| 27 | + if (equalRation) { |
| 28 | + if (imgWidth !== imgHeight) { |
| 29 | + Message.error(`图片比例必须为1:1`) |
| 30 | + reject() |
| 31 | + return false |
| 32 | + } |
| 33 | + } else { |
| 34 | + if (imgWidth !== width && imgHeight !== height) { |
| 35 | + Message.error(`图片分辨率必须为${width}像素x${height}像素`) |
| 36 | + reject() |
| 37 | + return false |
| 38 | + } |
| 39 | + } |
| 40 | + resolve() |
| 41 | + } |
| 42 | + image.src = e.target.result |
| 43 | + } |
| 44 | + reader.readAsDataURL(file) |
| 45 | + }) |
| 46 | + } |
| 47 | +} |
0 commit comments