SoFunction
Updated on 2025-03-01

js to upload and compress image effects

This article shares the specific code for uploading and compressing images for your reference. The specific content is as follows

Code:

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title></title>
  <script src="/jquery/3.2.1/"></script>
 </head>
 <body>
  <input type="file"  onchange="readFile(this)"/> 
  <img style=""  src="" alt="" />
  <script>
  function readFile(obj){ 
   var file = [0];  
   //Judge whether the type is a picture    if(!/image\/\w+/.test()){ 
      alert("Please make sure the file is image type"); 
      return false; 
    } 
    var reader = new FileReader(); 
    (file); 
     = function(e){
     dealImage(,{width:200},function(base){
     ('img').setAttribute('src',base)
     });
    } 
  } 
 
  /**
    * Image compression, default compression
    * @param {Object} path
    * The path passed in by the PC side can be a relative path, but the path that must be passed in on the mobile side is the absolute path of the photographic image storage.
    * @param {Object} obj
    * obj object has width, height, quality(0-1)
    * @param {Object} callback
    * The callback function has a parameter, the string data of base64
    */
  function dealImage(path, obj, callback){
   var img = new Image();
    = path;
    = function(){
   var that = this;
   // By default, scaled   var w = ,
   h = ,
   scale = w / h;
   w =  || w;
   h =  || (w / scale);
   var quality = 0.7; // The default image quality is 0.7   // Generate canvas   var canvas = ('canvas');
   var ctx = ('2d');
   // Create attribute node   var anw = ("width");
    = w;
   var anh = ("height");
    = h;
   (anw);
   (anh);
   (that, 0, 0, w, h);
   // Image quality   if( &&  <= 1 &&  > 0){
   quality = ;
   }
   // The smaller the quality value, the more blurry the drawn image   var base64 = ('image/jpeg', quality );
   // The callback function returns the value of base64   callback(base64);
   }
  }
  </script>
 </body>
</html>

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.