之前在公司开发过一段时间的移动端H5页面,有个功能就是要上传图片+压缩。参考了一下网上的方法,外加自己摸索的过程,最终实现了这个功能。后面在家闲的时候又加多了个长按选中图片,并且可以拖拽排序、拖拽到指定位置删除的功能。
github地址:代码地址
下面直接进入正题:
图片上传
图片上传用的是HTML的input标签实现的。核心就是把获取到的文件通过FileReader转换成图片,代码如下:
<input type="file" accept="image/*" capture="camera" @change="selectFile">
selectFile(event:any){
this.showAlert = false
if (event.target.files && event.target.files.length > 0) {
this.isLoading = true
let file:any = event.target.files[0]
let fr:any = new FileReader()
fr.readAsDataURL(file)
fr.onload = (imgObj:any) => {
let img:any = new Image()
img.src = imgObj.target.result
img.onload = (e:any) => {
// 这里就可以获取到上传的图片了
})
}
}
}
}
图片压缩
图片压缩用的是canvas重绘的方法实现的,具体代码如下:
// 省略上面的代码
fr.onload = (imgObj:any) => {
// 获取到图片文件后
let img:any = new Image()
img.src = imgObj.target.result
img.onload = (e:any) => {
Compress(img,e.path[0].height,e.path[0].width,(newImg:any) => {
this.imgList.push(newImg)
this.isLoading = false
// 待添加拖拽功能
})
}
}
/**
* 图片压缩
* @param img 图片对象
*/