文章出處

$('input[type="file"]').on('change',function(){
	var files = !!this.files ? this.files : [];
		
	// Create a new instance of the FileReader
	var reader = new FileReader();

	// Read the local file as a DataURL
	reader.readAsDataURL(files[0]);
	
	var blob = window.URL.createObjectURL(files[0]);//轉換為二進制blob文件
	var img=new Image();
	img.src=blob;
	img.onload = function(){
		var cvs = document.createElement('canvas');
		var ctx = cvs.getContext("2d");
		cvs.width=img.width*.2;
		cvs.height=img.height*.2;
		ctx.drawImage(this, 0, 0,img.width*.2,img.height*.2);
		var newImageData = cvs.toDataURL('image/jpg',1);
		
		//input file不能用于上傳base64,所以要再加一個input,同時把當前file的input賦值空,防止原圖片也上傳
		this.value="";
		$(this).next('input[type="hidden"]').val(newImageData);
	}
	// When loaded, set image data as background of div
	reader.onloadend = function(){
		$('#img').attr('src',this.result);//縮略圖
	}
})

  其中的newImageData即為新生成的壓縮后的圖片base64,上傳保存即可。


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜

    大師兄 發表在 痞客邦 留言(0) 人氣()