通过JS将图片File转为base64并压缩

/**
 * 
 * @param {需要转换的图片file} file 
 * @param {是否返回压缩后的base64} isCompression 
 * @param {转换成功后通过回调函数将结果返回} callback 
 */
export function imageToBase64(file, isCompression, callback) {
	// 判断图片类型
	if (file.type == 'image/jpeg' || file.type == 'image/png' || file.type == 'image/jpg') {
		var isJpg = true
	} else {
		jsJpg = false
	}

	// 判断图片大小
	const isLt2M = file.size / 1024 / 1024 < 2
	if (!isJpg) {
		this.$message.error('上传图片只能是jpg/png/jepg格式')
	}
	if (!isLt2M) {
		this.$message.error('上传图片大小不能超过2M')
	}

	// 创建一个HTML5的FileReader对象
	var reader = new FileReader()
	// 创建一个img对象
	var img = new Image()
	// let filename = file.filename
	if (file) {
		reader.readAsDataURL(file)
	}
	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也能直接显示出来)
				var canvas = document.createElement('canvas')
				var context = canvas.getContext('2d')
				// 图片原始尺寸
				var originWidth = this.width
				var originHeight = this.height
				// 最大尺寸限制,可通过设置宽高来实现图片压缩程度
				var maxWidth = 300,
					maxHeight = 300
				// 目标尺寸
				var 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替代
				 */
				var newUrl = canvas.toDataURL('image/jpeg', 0.02)
				if (isCompression) { // 返回压缩后的base64
					callback(newUrl)
				} else { // 返回不压缩的base64
					callback(e.target.result)
				}
			}
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值