Harish Lalwani
Harish Lalwani

Reputation: 774

Client side resize Image and posting using canvas

I am trying to implement client side resizing of images and then posting them to backend. I dont know much about canvas. There are 9 images which I have to upload simultaneously. What I need to do is

Upvotes: 1

Views: 503

Answers (1)

markE
markE

Reputation: 105035

How to further lessen upload "weight"

Looks like you're ok with "lossy" jpg so you could additionally set the jpeg's image quality to a medium value to make it even more "light weight".

var jpeg = canvas.toDataURL('image/jpeg',0.50);

To process 9 jpegs, you can:

  • Accumulate all 9 jpeg encoded strings in an array: var jpegs=[];
  • When ready to send, use JSON to stringify the javascript array: var jsonJpegs=JSON.stringify(jpegs)
  • Optionally, use a javascript ZIP script to further reduce the weight of the encoded images. One example zip library: https://stuk.github.io/jszip/

Annotated code and a Demo:

// canvas vars
var canvas=document.createElement("canvas");
var ctx=canvas.getContext("2d");

// define max resulting image width,height (after resizing)
var maxW=100;
var maxH=100;

// listen for user to select files
var input = document.getElementById('input');
input.addEventListener('change', handleFiles);

function handleFiles(e) {
  var img = new Image;
  img.onload = function(){
    var iw=img.width;
    var ih=img.height;
    // scale down, if necessary
    if(iw>maxW || ih>maxH){
      var scale=Math.min((maxW/iw),(maxH/ih));
      iw*=scale;
      ih*=scale
    }
    // set canvas width/height to scaled size
    canvas.width=iw;
    canvas.height=ih;
    // draw+scale the img onto the canvas
    ctx.drawImage(img,0,0,iw,ih);
    // create a jpeg URL (with medium quality to save "weight") 
    var jpg=canvas.toDataURL('image/jpeg',0.60);
    // In Demo: add the jpg to the window
    // In production, accumulate jpg's & send to server
    $('<img />',{src:jpg}).appendTo('body');
  }
  // In Demo: Just process the first selected file 
  // In production: process all selected files 
  img.src = URL.createObjectURL(e.target.files[0]);
}
img{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Select an image file for resizing</h4>
<input type="file" id="input"/><br>

Upvotes: 1

Related Questions