是不是有人和我一样在业务中遇到图片转base64的问题,在网上找了很多都不行,这个配合上传组件复制可用,直接上代码!
changeImageIsBase64(image) {
let that = this;
let imageFile = image.file;
let isJpg = false;
// 判断图片类型
if (imageFile.type == 'image/jpeg' || imageFile.type == 'image/png' || imageFile.type == 'image/jpg') {
isJpg = true
}
console.log(imageFile.type)
// 判断图片大小
const isLt2M = imageFile.size / 1024 / 1024 < 0.1
if (!isJpg) {
that.$notify.error('转码只能是jpg/png/jepg格式')
}
if (!isLt2M) {
that.$notify.error('上传图片大小不能超过100k')
}
// 创建一个HTML5的FileReader对象
let reader = new FileReader()
// 创建一个img对象
let img = new Image()
// let filename = file.filename
if (imageFile) {
reader.readAsDataURL(imageFile)
}
if (isJpg && isLt2M) {
reader.onload = (e) => {
// let base64Str = reader.result.split[','][1]
img.src = e.target.result
// base64地址图片加载完毕后执行
img.onload = function () {
// 缩放图片需要canvas(也可以在DOM中直接定义canvas标签,这样就能把压缩完的图片不转base64也能直接显示出来)
let canvas = document.createElement('canvas')
let context = canvas.getContext('2d')
// 图片原始尺寸
let originWidth = this.width
let originHeight = this.height
// 最大尺寸限制,可通过设置宽高来实现图片压缩程度
let maxWidth = 300
let maxHeight = 300
// 目标尺寸
let targetWidth = originWidth,
targetHeight = originHeight
// 图片尺寸超过最大尺寸限制
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > maxWidth / maxHeight) {
// 更改宽度,按照宽度限定尺寸
targetWidth = maxWidth
targetHeight = Math.round(maxWidth * (originHeight / originWidth))
} else {
targetHeight = maxHeight
targetWidth = Math.round(maxHeight * (originWidth / originHeight))
}
}
// 对图片进行缩放
canvas.width = targetWidth
canvas.height = targetHeight
// 清除画布
context.clearRect(0, 0, targetWidth, targetHeight)
/** 图片压缩
* 第一个参数是创建的img对象
* 第二三个参数是左上角坐标
* 后两个参数是画布区域宽高
*/
context.drawImage(img, 0, 0, targetWidth, targetHeight)
/** 压缩后的base64文件
* 第一个参数可以为image/jpeg或image/webp类型的图片
* 第二个参数设置图片质量取值0-1,超出则以默认值0.92替代
*/
let newUrl = canvas.toDataURL('image/jpeg', 0.02)
// if (isCompression) { // 返回压缩后的base64
// callback(newUrl)
// } else { // 返回不压缩的base64
// callback(e.target.result)
// }
that.icon = newUrl;
}
}
}
}
(注:这个代码是很久之前在网上找的我修改了一下,找不到具体是哪位的了,要是原作者看到这个代码和自己的很像请私聊我到时候定会改为转载!)