js generates picture thumbnails through canvas

  • 2021-08-28 19:24:25
  • OfStack

Nowadays, most web applications save pictures of several sizes at the same time when uploading pictures. The technical term is to generate thumbnails, and the general method for generating thumbnails 1 is to generate them through the back-end language php, etc. However, in order to decompress the server, we may start from the front end, and build thumbnails of different sizes and pass them to the back end, which only needs to store the pictures sent from the front end.

Using Canvas, we can easily generate pictures of various sizes, as follows:


function resizeImage(src,callback,w,h){
 var canvas = document.createElement("canvas"),
  ctx = canvas.getContext("2d"),
  im = new Image();
  w = w || 0,
  h = h || 0;
 im.onload = function(){
  // Original dimensions for incoming scaling dimensions 
  !w && (w = this.width);
  !h && (h = this.height);
  // Take the maximum length and width as the basis for the final generation of pictures 
  if(w !== this.width || h !== this.height){
   var ratio;
   if(w>h){
    ratio = this.width / w;
    h = this.height / ratio;
   }else if(w===h){
    if(this.width>this.height){
     ratio = this.width / w;
     h = this.height / ratio;
    }else{
     ratio = this.height / h;
     w = this.width / ratio;
    }
   }else{
    ratio = this.height / h;
    w = this.width / ratio;
   }
  }
  // Take the passed-in length and width as the final size of the generated picture 
  if(w>h){
   var offset = (w - h) / 2;
   canvas.width = canvas.height = w;
   ctx.drawImage(im,0,offset,w,h);
  }else if(w<h){
   var offset = (h - w) / 2;
   canvas.width = canvas.height = h;
   ctx.drawImage(im,offset,0,w,h);
  }else{
   canvas.width = canvas.height = h;
   ctx.drawImage(im,0,0,w,h);
  }
  callback(canvas.toDataURL("image/png"));
 }
 im.src = src;
}

Online example address: http://demo.ofstack.com/js/2020/thumbnail/. The picture material is a screenshot of a photo frame making application we made. Interested friends can contact me. Let's discuss and play.


Related articles: