1.获取文件后将文件转换为blod对象
2.将blod类型转化为base64个,改变图片的宽高,从而降低图片大小
3.将base转化为blob对象
4.blob对象转化为file对象
个人记录,有更好的方法可以,在评论一起探讨
/**
* 压缩图片
* */
export function ImageSize(file) {
return new Promise(resolve => {
let reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = (ev) => {
let blob = new Blob([ev.target.result]);
window.URL = window.URL || window.webkitURL;
let blobURL = window.URL.createObjectURL(blob);
let image = new Image();
image.src = blobURL;
image.onload = (e) => {
let suffix = file.name.split('.')[file.name.split('.').length - 1];
let base64 = resize(image, suffix, 750, 0);
let blobFile = dataURItoBlob(base64);
let fileObj = blobToFile(blobFile, file.name);
resolve(fileObj);
};
};
});
}
/**
* @param {object} img image对象
* @param {string} type 类型
* @param {number} max_width 最大宽度
* @param {number} max_height 最大高度
* */
// eslint-disable-next-line camelcase
export function resize(img, type, max_width, max_height) {
let canvas = document.createElement('canvas');
let width = img.width;
let height = img.height;
// eslint-disable-next-line camelcase
let maxWidth = !isNaN(max_width) ? max_width : 0;
// eslint-disable-next-line camelcase
let maxHeight = !isNaN(max_height) ? max_height : 0;
// 在这里图片是等比例缩放的,调用方法时填入图片允许的最大宽度或者是最大的高度
// 如果最大宽度为0 则按照最大高度固定,宽度自适应的方式来实现
// 如果是最大高度为0,则按照最大的宽度来实现
if (maxWidth === 0) {
if (height > maxHeight) {
width = Math.round(width *= maxHeight / height);
height = maxHeight;
}
}
if (maxHeight === 0) {
if (width > maxWidth) {
height = Math.round(height *= maxWidth / width);
width = maxWidth;
}
}
canvas.width = width;
canvas.height = height;
let ctx = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
type = type === 'jpg' ? 'jpeg' : type;
return canvas.toDataURL('image/' + type, 0.3); // 这里的0.3值的是图片的质量
}
/**
* 将 Base64 编码转换为 Blob 对象
* */
export function dataURItoBlob(dataURI) {
const byteString = atob(dataURI.split(',')[1]);
const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
const ab = new ArrayBuffer(byteString.length);
const ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
const blob = new Blob([ab], { type: mimeString });
return blob;
}
/**
* Blob 对象转换为 File 对象
* @param {Object} theBlob blob格式
* @param {String} fileName 文件名称
* */
export function blobToFile(theBlob, fileName) {
theBlob.lastModifiedDate = new Date();
theBlob.name = fileName;
return theBlob;
}