js image to base64 and compressed

/* 2015-09-28 upload pictures*/
     function convertImgToBase64(url, callback, outputFormat){
         var canvas = document. createElement('CANVAS');
         var ctx = canvas. getContext('2d');
         var img = new Image;
         img.crossOrigin = 'Anonymous';
         img.onload = function(){
           var width = img. width;
           var height = img. height;
           // Compressed by 4 times
           var rate = (width<height ? width/height : height/width)/4;
           canvas.width = width*rate;
           canvas.height = height*rate;
           ctx.drawImage(img,0,0,width,height,0,0,width*rate,height*rate);
           var dataURL = canvas.toDataURL(outputFormat || 'image/png');
           callback. call(this, dataURL);
           canvas = null;
         };
         img.src = url;
       }
        function getObjectURL(file) {
             var url = null;
             if (window.createObjectURL!=undefined) { // basic
               url = window.createObjectURL(file);
             } else if (window.URL!=undefined) { // mozilla(firefox)
               url = window.URL.createObjectURL(file);
             } else if (window. webkitURL!=undefined) { // web_kit or chrome
               url = window. webkitURL. createObjectURL(file);
             }
             return url;
       }
      // The front end only needs to bind the change event to the input file (the above two methods are ignored) huodong-msg is the input class
       $('.huodong-msg').bind('change', function(event){
             var imageUrl = getObjectURL($(this)[0].files[0]);
             convertImgToBase64(imageUrl, function(base64Img){
               // base64Img is converted base64, put it in img src and display it directly on the foreground (<img src="data:image/jpg;base64,/9j/4QMZRXh...." />)
               alert(base64Img);
               // Base64 image transfer does not require base64 prefix data:image/jpg;base64
               alert(base64Img. split(",")[1]);
             });
             event. preventDefault();
         });
     /* 2015-09-28 */
copy code

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish