各类转Base64
一、图片file转base64
/*
* 图片file转base64
* @param {String} file 图片file
* */
Vue.prototype.$toBase64 = function (file) {
return new Promise(function (resolve, reject) {
const reader = new FileReader()
let imgResult = ''
reader.readAsDataURL(file)
reader.onload = function () {
imgResult = reader.result
}
reader.onerror = function (error) {
reject(error)
}
reader.onloadend = function () {
resolve(imgResult)
}
})
}
二、url网络图片转base64
/*
* 图片url转base64
* @param {String} url 图片url
* @param {callback} cb 回调函数
* */
Vue.prototype.$urlToBase64 = function (url, cb) {
var dataURL = null
var canvas = document.createElement('canvas')
var ctx = canvas.getContext('2d')
var img = new Image()
img.crossOrigin = 'Anonymous'
img.onload = function () {
canvas.height = img.height
canvas.width = img.width
ctx.drawImage(img, 0, 0)
dataURL = canvas.toDataURL('image/png')
cb && cb(dataURL)
canvas = null
}
img.src = url
}