Upload picture compression package

Picture upload upload pictures usually take into account the size of the big picture is compressed upload, on the one hand is to reduce the pressure on the server, on the other hand but also to improve the user experience, reduce upload time.

Image compression can compress images with drawImage method of canvas.

By calling UpladFile method, and pass the relevant parameters.

id: id value input box

Address background uploading files: url

maxNum: Maximum size - Unit M

obj: parameter object can have attributes such as width height quality

/ * 
File: a file (a picture format type), 
W: the width of a file is compressed, the smaller the width, the smaller the byte 
objDiv: is a container or a callback function 
* / 
function photoCompress (File, W, objDiv ) { 
	var READY = the FileReader new new (); 
	/ * read the contents of the specified start Blob object or File object when the read operation is completed, the readyState property becomes DONE, if set onloadend event handler is. at the same time the call, result in the attribute comprises a data:.. the string of the URL format to represent the contents of the read file * / 
	ready.readAsDataURL (file); 
	ready.onload = function () { 
		var Re = this.result ; 
		canvasDataURL (Re, W, objDiv); 
	} 
} 
function canvasDataURL (path, obj, the callback) { 
	var IMG = new new Image (); 
	img.src = path; 
	img.onload = function () { 
		var = that the this; 
		/ / default scale compression 
		var W = that.width, 
			H = that.height,
			scale = w / h;
		w = obj.width || w;
		h = obj.height || (w / scale);
		var quality = 0.7;  // 默认图片质量为0.7
		//生成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, 0, w, h);
		// 图像质量
		if(obj.quality && obj.quality <= 1 && obj.quality > 0){
			quality = obj.quality;
		// Quality smaller the value, the more blurry the image drawn
		}
		canvas.toDataURL base64 = var ( 'Image / JPEG', Quality); 
// upload method
		// the return value of the callback function is base64 
		// display image, according to the needs 
		// document.querySelectorAll ( '# preImg') [0] = base64 .src; 
		the callback (base64); 
	} 
} 
/ ** 
 * images will base64 url data into Blob 
 * @param URLData 
 * Base64 image data represented by the url way 
 * / 
function convertBase64UrlToBlob (URLData) { 
	var urlData.split ARR = ( ','), MIME ARR = [0] .match (/ :( .? *); /) [. 1], 
		BSTR = atoB (ARR [. 1]), = n-bstr.length, new new Uint8Array u8arr = (n-); 
	the while (n--) { 
		u8arr [n-] = bstr.charCodeAt (n-); 
	} 
	return new new Blob ([u8arr], {type: MIME}); 
} 
var XHR;
// obj can pass parameters Quality height width 
function UpladFile (ID, URL, maxNum, obj) { 
	var fileObj = document.getElementById (ID) .files [0]; // Get JS file object 
	var url = url; // receiving background address upload file 
	var form = new FormData (); // FormData objects 

	if (fileObj.size / 1024> 1024 * maxNum) {// greater than 1M, compressed upload 
		photoCompress (fileObj, obj}, function (base64Codes) { 
			console.log ( "compressed:" base64Codes.length + / 1024 + "" + base64Codes); 
			var BL = convertBase64UrlToBlob (base64Codes); 
			form.append ( "File", BL, "_ File" + Date.parse (new new a Date ()) + ". jpg" ); // file object 
			xhr = new XMLHttpRequest (); // XMLHttpRequest objects 
			xhr.open ( "post", url, true); // post embodiment, url server requests an address, true this parameter specifies whether the request is an asynchronous process. 
			XHR.onload = uploadComplete; // request is completed 
			xhr.onerror = uploadFailed; // request failed 

			xhr.upload .onprogress = progressFunction;// call the method [upload progress achieved]
			xhr.upload.onloadstart = function () {// begin uploading method 
				ot = new Date () getTime ( );. // set the start time to upload 
				oloaded = 0; // set when uploading begins to upload file sizes 0 
			}; 

			xhr.send (form); // start uploading, form data transmission 
		}, obj); 
	} // the else {less 1M picture upload 
		form.append ( "file", fileObj) ; // file object 
		xhr = new XMLHttpRequest (); // XMLHttpRequest objects 
		xhr.open ( "post", url, true); // post embodiment, url requests for the server address, true this parameter specifies whether the request is asynchronous processing. 
		xhr.onload = uploadComplete; // request is completed 
		xhr.onerror = uploadFailed; // request failed 

		xhr.upload.onprogress = progressFunction; // call the upload progress implemented method [] 
		xhr.upload.onloadstart = function () {// upload the method begins execution  
			ot = new Date () getTime ( );. // set the start time to upload
			oloaded = 0; // set uploading begins to upload the file size is 0 
		}; 

		xhr.send (form); // start uploading, data transmission form 
	} 
} 

// upload success response 
function uploadComplete (EVT) { 
	// off completely received file service result returned 

	var = the JSON.parse Data (evt.target.responseText); 
	IF (data.success) { 
		the console.log ( "uploaded successfully!"); 
	} {the else 
		the console.log ( "failed to upload ! "); 
	} 

} 
// failed to upload 
function uploadFailed (evt) { 
	console.log (" upload failed ");! 
} 
// cancel the upload 
function cancleUploadFile () { 
	xhr.abort (); 
} 

// upload progress implementation upload process will call this method frequently 
function progressFunction (EVT) { 
	var progressBar = document.getElementById ( "progressBar"); 
	var percentageDiv = document.getElementById ( "PERCENTAGE"); 
	// needs to be transmitted is event.total the total number of bytes, event.loaded bytes already transferred. If event.lengthComputable is not true, then event.total equal to 0
	IF (evt.lengthComputable) {// 
		progressBar.max = evt.total; 
		progressBar.value = evt.loaded; 
		percentageDiv.innerHTML = Math.round (evt.loaded / evt.total * 100) + "%"; 
	} 
	var = document.getElementById time ( "time"); 
	var new new NT = a Date () the getTime ();. // get the current time 
	var pertime = (nt-ot) / 1000; // this method calculated the last call now the time difference in units of S 
	OT = new new a Date () the getTime (); // reassigned time, for the next calculation. 
	var perload = evt.loaded - oloaded; // calculate the upload file size segment, the unit B 
	oloaded = evt.loaded; // reassigned uploaded file size for the next calculation 
	// upload speed calculating 
	var speed = perload / pertime; // unit B / S 
	var = speed bspeed; 
	var units = 'B / S '; // name 
		units =' K / S ';
	}
	if(speed/1024>1){ 
	if (speed / 1024>1){
		Speed = Speed / 1024;
		Speed = Speed / 1024; 
		Units = 'M / S'; 
	} 
	Speed speed.toFixed = (. 1); 
	// time remaining 
	var resttime = ((evt.total-evt.loaded ) / bspeed) .toFixed (1); 
	the console.log ( 'speed:' + speed + units + 'time remaining' + + resttime 'S'); 
	IF (bspeed == 0) the console.log ( 'Upload canceled'); 
}

  

Guess you like

Origin www.cnblogs.com/zihua/p/11125138.html