Search code examples
javascriptcanvashtml5-canvasresize-image

How to resize canvas contents and upload image to server?


I have been trying to figure out how I could resize the canvas contents to get roughly a 100x100 thumbnail and upload it to the server. I would like to keep my existing canvas in its current size, because all these actions have to be invisible to the user.

I know I can get the contents in the current size of the canvas by using toDataURL, but how could I resize it and then upload to the server?

var image = canvas.toDataURL("image/png");

Solution

  • Thanks to Alexander Kremenets I managed to put together the code I needed. I used the Hermite resize from the question Alexander linked. Also combined code from other questions coming up with this:

    var originalCanvas = document.getElementById("c");
    // Create canvas for resizing
    var resizeCanvas = document.createElement("canvas");
    resizeCanvas.height = originalCanvas.height;
    resizeCanvas.width = originalCanvas.width;
    
    var resizeCtx = resizeCanvas.getContext('2d');
    // Put original canvas contents to the resizing canvas
    resizeCtx.drawImage(originalCanvas, 0, 0);
    
    // Resize using Hermite resampling
    resampleHermite(resizeCanvas, resizeCanvas.width, resizeCanvas.height, 150, 90);
    
    // Use the resized image to do what you want
    var image = resizeCanvas.toDataURL("image/png");