微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

uniapp 图片压缩上传

我试了很多方法最后

都很拉跨

最后…

直接调用这个addImg()


			
			// 压缩图片02
			photoCompress(file,objdiv) {
				var ready = new FileReader();
				ready.readAsDataURL(file);
				const _this = this;
				ready.onload = function() {
					var fileResult = this.result;
					_this.canvasDataURL(fileResult,objdiv)
				}
			},canvasDataURL(path,callback) {
				var img = new Image();
				img.src = path;
				var objCompressed = {}
				img.onload = function() {
					var that = this;
					//认压缩后图片规格
					var quality = 0.7;
					var w = that.width;
					var h = that.height;
					var scale = w / h;
					//实际要求
					w = objCompressed.width || w;
					h = objCompressed.height || (w / scale);
					//生成canvas
					var canvas = document.createElement('canvas');
					var ctx = canvas.getContext('2d');
					// 创建属性节点
					var anw = document.createAttribute("width");
					anw.nodeValue = w;
					var anh = document.createAttribute("height");
					anh.nodeValue = h;
					canvas.setAttributeNode(anw);
					canvas.setAttributeNode(anh);
					ctx.drawImage(that,0,w,h);

					var base64 = canvas.toDataURL('image/jpeg',quality);
					// 回调函数返回base64的值
					callback(base64);
				}
			},dataURLtoFile(dataurl,filename) {
					var arr = dataurl.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 File([u8arr],filename,{ type: mime });
			},// 压缩图片02
			
			addImg(){
				uni.chooseImage({
					success:(res) =>{
					
						let i = 0
						
						// 压缩上传02
						for (let file of res.tempFiles) {
							// this.multipartUpload(i,file)
							const imgSize = res.tempFiles[i] && res.tempFiles[i].size ? res.tempFiles[i].size : 0;
							const imgName = res.tempFiles[i]&&res.tempFiles[i].name?res.tempFiles[i].name:'';
							// console.log(imgSize,file)
							this.photoCompress(res.tempFiles[i],(base64Codes) => {
								var fl = this.dataURLtoFile(base64Codes,imgName)
								// console.log(fl.size,fl,"压缩后的文件")
								
							})
							i++
						}
						// 压缩上传02
					
						
						
					}
				});
			},

转发于https://blog.csdn.net/baidu_41604826/article/details/111224603

在此表达感谢

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐