图片裁剪并上传到阿里云oss

此案例需要基于我前面3遍文章的代码,建议先行阅读。

阿里云OSS图片上传(java web直传)https://blog.csdn.net/u011628753/article/details/110876234

前端图片裁剪并上传到七牛云kodo https://blog.csdn.net/u011628753/article/details/110877703

js图片压缩 https://blog.csdn.net/u011628753/article/details/110878470

附:plupload插件的API:https://www.plupload.com/docs/

逻辑思想

将dataUrl(base64)转换为file对象,利用plupload.js插件的uploader.addFile添加file文件,然后再上传文件。(dataUrl是已经裁剪好的文件)

需要调用的js

function getInfo(event){
		
		let reader = new FileReader();
		//这里把一个文件用base64编码
		reader.readAsDataURL(event.target.files[0]);			
		reader.onload = function(e){
			let newImg = new Image();
			//获取编码后的值,也可以用this.result获取
			newImg.src = e.target.result;
			newImg.onload = function () {
				/* 获取  this.height tthis.width*/
				var dataURL = compress(newImg,this.width,this.height,0.8);
				/*为了兼容ios 需要 dataURL-> blob -> file */
				var blob = dataURLtoBlob(dataURL);		// dataURL-> blob 
				var file = blobToFile(blob, '999');		// blob -> file
				console.log("得到文件:"+file);	
				console.log("压缩后大小:"+file.size/1024);				
				$("body").append("<img src='" + dataURL + "' />");
				
			}
		}
		
	}	
			
	function compress(img, width, height, ratio) { // img可以是dataURL或者图片url
		/*	如果宽度大于 750 图片太大 等比压缩 	*/
		if(width > 750){
			var ratio = width/height;
			width = 750;
			height = 750/ratio;
		}		
		var canvas, ctx, img64;
		canvas = document.createElement('canvas');
		canvas.width = width;
		canvas.height = height;
		

		ctx = canvas.getContext("2d");
		ctx.drawImage(img, 0, 0, width, height);
		/* canvas.toDataURL(mimeType(图片的类型), qualityArgument(图片质量)) */
		img64 = canvas.toDataURL("image/jpeg", ratio);

		return img64; // 压缩后的base64串
	}
	//将base64转换为blob
	function dataURLtoBlob (dataurl) { 
		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 Blob([u8arr], { type: mime });
	}
	//将blob转换为file
	function blobToFile(theBlob, fileName){
	   theBlob.lastModifiedDate = new Date();
	   theBlob.name = fileName;
	   return theBlob;
	}

猜你喜欢

转载自blog.csdn.net/u011628753/article/details/110878292