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

在此表达感谢

相关文章

咱们国内现在手机分为两类,Android手机与苹果手机,现在用的...
前言 上一篇做了php的微信登录,所以也总结一下Java的微信授...
前言 上一篇文章写到如何上架IOS应用到Appstore,其中漏掉了...
文件-新建-1.项目 ┌─uniCloud 云空间目录,阿里云为uniClo...
Flexbox #Flex 容器 Flex 是 Flexible Box 的缩写,意为&...
globalStyle 用于设置应用的状态栏、导航条、标题、窗口背景...