话不多,看代码!
1、将图片的url转换成base64
urlTobase64(url) {
var that = this
var img = new Image()
img.src = url + '?time=' + new Date().valueOf() // 加上时间结尾,处理缓存
//支持http跨域图片。需要后端设置图片支持跨域为*(如果后端不处理,加上这行会无法显示图片,导致拿不到base64)
img.setAttribute('crossOrigin', '*')
if (url) {
img.onload = function() {
var base64Url = that.getBase64Image(img)
console.log(base64Url) // 最终拿到的base64值
}
}
},
getBase64Image(img) {
var canvas = document.createElement('canvas')
canvas.width = img.width
canvas.height = img.height
var ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, img.width, img.height)
const dataURL = canvas.toDataURL('image/jpeg') // 可根据图片后缀,动态变换如 image/png
return dataURL
},
2、将图片的file类型转换成base64,压缩图片大小
html:
<el-upload
class="up-btn"
action=""
list-type="picture-card"
:multiple="false"
:show-file-list="false"
:before-upload="beforeAvatarUpload">
<i class="el-icon-plus"></i>
</el-upload>
js:
// 上传图片
beforeAvatarUpload(file) {
// 判断扩展名
const tmpcnt = file.name.lastIndexOf('.')
const exname = file.name.substring(tmpcnt + 1)
const names = ['jpg', 'jpeg', 'png']
if (names.indexOf(exname) < 0) {
this.$message.error('不支持的格式!')
return
}
if (file.size > 1024 * 1024 * 5) {
this.$message.error('图片大小最大5M')
return
}
this.urlTobase64(file)
},
// 图片转base64
urlTobase64(file) {
var that = this
var reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = function(e) { // 读取完毕后调用接口
// 获取到base64值
var img64 = e.target.result
// 图片大于1M的时候执行压缩
if (img64.length > 1024 * 1024 * 1) {
var size = (1024 * 1024 * 1) / img64.length
that.compress(file, img64, size) // size越小压缩效果越大
}
}
},
// 压缩图片
compress(file, img64, size) {
var that = this
var img = document.getElementById('base64Url')
var width, height
// 加载完成执行
img.onload = function() { // base64地址图片加载完毕后执行
width = img.width
height = img.height
var canvas = document.createElement('canvas')
var ctx = canvas.getContext('2d')
// var initSize = img.src.length
canvas.width = width
canvas.height = height
// 铺底色
ctx.fillStyle = '#fff'
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(img, 0, 0, width, height)
// 进行最小压缩后的base64
var base64Url = canvas.toDataURL('image/jpeg', size)
console.log(base64Url)
}
}