uniapp H5图片压缩上传

/**
 *  参数说明:
 *  imgSrc 图片url
 *  scale缩放比例 0-1
 *  type 返回图片类型  默认blob 
 *  callback 回调设置返回值 
*/
export function translate(imgSrc, scale, type , callback) {
	var img = new Image();
	img.src = imgSrc;
	img.onload = function() {
		var that = this;
		var h = that.height; // 默认按比例压缩
		var w = that.width;
		var canvas = document.createElement('canvas');
		var ctx = canvas.getContext('2d');
		var width = document.createAttribute("width");
		width.nodeValue = w;
		var height = document.createAttribute("height");
		height.nodeValue = h;
		canvas.setAttributeNode(width);
		canvas.setAttributeNode(height);
		ctx.drawImage(that, 0, 0, w,h);
		var base64 = canvas.toDataURL('image/jpeg', scale);//压缩比例
		canvas = null;
		if(type == 'base64'){
			callback(base64);
		}else{
			var blob = base64ToBlob(base64); 
			var blobUrl = window.URL.createObjectURL(blob);//blob地址
			callback(blobUrl);
		}
	}
}
export function base64ToBlob(base64) { // base转Blob
	var arr = base64.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {
		type: mime
	});
}

  • 引入
import {translate} from './compress.js'
  • 使用
uni.chooseImage({
	count: that.imgLength,
	sizeType: ['compressed'],
	sourceType: ['album', 'camera'],
	success: (res) => {
		if (that.tempFilePaths.length >= that.imgLength) {
			uni.showToast({
				title: '最多可上传' + that.imgLength + '张照片哦~',
				icon: 'none'
			})
			return
		}
		for (let i = 0; i < res.tempFilePaths.length; i++) {
			if (that.tempFilePaths.length < that.imgLength) {
				translate(res.tempFilePaths[i],0.1,'base64',base64Url=>{
					that.tempFilePaths.push(base64Url)
				})
			}
		}				
	}
})	
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值