그림 을 압축 하여 base 64 문자열 로 변환 합 니 다.

18025 단어 js
그림 압축
/*
    
file:     (       ),
w:           ,    ,    
objDiv:           
photoCompress()
 */
function photoCompress(file,w,objDiv){
     
    var ready=new FileReader();
    /*       Blob   File      .         ,readyState       DONE,     onloadend      ,    .  ,result        data: URL                 .*/
    ready.readAsDataURL(file);
    ready.onload=function(){
     
        var re=this.result;
        canvasDataURL(re,w,objDiv)
    }
}

function canvasDataURL(path, obj, callback){
     
    var img = new Image();
    img.src = path;
    img.onload = function(){
     
        var that = this;
        //        
        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   ,          
        var base64 = canvas.toDataURL('image/jpeg', quality);
        //       base64  
        callback(base64);
    }
}

/**
 *   base64   url     Blob
 * @param urlData  url     base64    
 */
function convertBase64UrlToBlob(urlData){
     
    var arr = urlData.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});
}

사용 예시
<input type="file" id="file" @change="changepic()" style="width:200px" class="form-control" v-model="imageFile"/>
<img src="" id="previewsImg" width="200">
  var pic = $('#file')[0].files[0];
  if(pic.size/1024 > 100){
      //  100k,      
  //    
  photoCompress(pic, {
     
       quality: 0.2
   }, function(base64Codes){
       //    
   		//base64Codes         base64   
   		//  base64       Blob               
       var bl = convertBase64UrlToBlob(base64Codes);
       //fd.append("imageFile", bl, "file_"+Date.parse(new Date())+".jpg"); //     
       //vm.uploading(fd);
   });
}

그림 미리 보기
 changepic: function() {
     
	var reads= new FileReader();
	f=document.getElementById('file').files[0];
	if(f == undefined || f == ''){
     
		return;
	}
	reads.readAsDataURL(f);
	reads.onload=function (e) {
     
		document.getElementById('previewsImg').src=this.result;
	};
}

좋은 웹페이지 즐겨찾기