// 压缩图片需要的一些元素和对象
let reader = new FileReader(), img = new Image();
// 选择的文件对象
let file = null;
// 缩放图片需要的canvas
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
export default class Text extends BaseComponent {
componentWillMount() {
const self = this
// base64地址图片加载完毕后
img.onload = function (){ //这里用箭头函数,blob打印出来时null
// 图片原始尺寸
let originWidth = this.width;
let originHeight = this.height;
// 最大尺寸限制
let maxWidth = 800, maxHeight = 480;
// 目标尺寸
let targetWidth = originWidth, targetHeight = originHeight;
// 图片尺寸超过400x400的限制
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > maxWidth / maxHeight) {
// 更宽,按照宽度限定尺寸
targetWidth = maxWidth;
targetHeight = Math.round(maxWidth * (originHeight / originWidth));
// targetHeight = maxHeight;
} else {
targetHeight = maxHeight;
// targetWidth = maxWidth;
targetWidth = Math.round(maxHeight * (originWidth / originHeight));
}
}
// canvas对图片进行缩放
canvas.width = targetWidth;
canvas.height = targetHeight;
// 清除画布
context.clearRect(0, 0, targetWidth, targetHeight);
// 图片压缩
context.drawImage(img, 0, 0, targetWidth, targetHeight);
// canvas转为blob并上传
canvas.toBlob( (blob) => {
console.log(blob, '压缩后图片')
console.log(`压缩图片大小:${blob.size}`)
// uploadFileImg为上传文件函数,由于onload函数不是箭头函数,this,uploadFileImg报错,所以这里用self
self.uploadFileImg(blob, file.name || '');
// if ('msSaveOrOpenBlob' in navigator){
// window.navigator.msSaveOrOpenBlob(new Blob([Image]), 'testsize' + '.png');
// }else{
// // let url = window.URL.createObjectURL(new Blob([Image], { type: "image/jpeg" }));
// let url = window.URL.createObjectURL(blob)
// let link = document.createElement('img');
// // link.style.display = 'none';
// link.src = url;
// // link.setAttribute('download', filename + '.wav');
// document.body.appendChild(link);
// // link.click();
// }
}, file.type || 'image/png');
};
// 文件base64化,以便获知图片原始尺寸
reader.onload = function(e) {
img.src = e.target.result; // 也可以用来展示图片
};
}
// 选择照片
handleFileChangeImg = (e) => {
const files = e.target.files;
// 如果拍摄了照片 则上传
if (files && files.length) {
file = files[0];
// 展示图片
this.setState({
selectImg: URL.createObjectURL(file)
})
console.log(file, '原始图片')
console.log(`原始图片大小:${file.size}`)
// 选择的文件是图片
if (file.type.indexOf("image") === 0) {
reader.readAsDataURL(file);
}
}
}
render() {
retrun(
<input onChange={this.handleFileChangeImg} type="file" name="video" accept="image/*" capture="user" />
)
}
}
原文参考地址:https://www.zhangxinxu.com/wordpress/2017/07/html5-canvas-image-compress-upload