Image resizing client-side with javascript before upload to the server

Javascript resize Image Before Upload

I have googled to find a solution for image resizing in client side with JavaScript before it uploads to the server. I got some solutions but they are not worked in all the browsers, some works in Firefox, some in chrome but not in all the browsers. So I am decided to find a way on my own.

As I see canvas concept works perfectly in Chrome but it does not work in Firefox and Safari browsers.  The problem is when we upload an image, file reader reads and provides us the image properties like name, filetype and source of the image(src) which will help in image resizing. When i do console.log the properties are coming quite well in all the browsers when i tried to read img.width and img.height to assign to some other variables which i am going to use for canvas width and height they don’t work in Firefox and Safari but works fine in  Chrome browser. if img variable returns 0 as width and height then the ctx.DrawImage function won’t work and it will return the image src as “data,” which is a wrong one. So later i used setTimeout to sort this problem out and everything works fine in all the browsers. The delay which we give in the setTimeout function is doing the tricky job to get the uploaded file properties.

Below is the code for the solution of image resize client side before uploading to the server with javascript. If you find anything not working please do comment with your issue we will try to address it ASAP


<html>
<head>
<title>Resize image</title>

</head>
<body>
<div>
<input id="imageFile" type="file"><input type="button" value="Resize Image" onclick="ResizeImage()"/>
<img src="" id="output">

</div>

<script type="text/javascript">

function ResizeImage() {
var filesToUpload = document.getElementById('imageFile').files;
var file = filesToUpload[0];

// Create an image
var img = document.createElement("img");
// Create a file reader
var reader = new FileReader();
// Set the image once loaded into file reader
reader.onload = function(e) {
//img.src = e.target.result;

var img = new Image();

img.src = this.result;

setTimeout(function(){
var canvas = document.createElement("canvas");

var MAX_WIDTH = 300;
var MAX_HEIGHT = 300;
var width = img.width;
var height = img.height;

if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/jpeg");
document.getElementById('output').src = dataurl;
},100);
}
// Load files into file reader
reader.readAsDataURL(file);
}

</script>
</body>
</html>

Download / Demo

You may also like...