Resize Image using Javascript

javaScript resize image; In this tutorial, i am going to show you how to resize an image using javascript and after resizing the image how-to shows the preview of resizing an image.

javaScript Resize Image Example

Using the following javaScipt code, you can easily resize image in javaScript; as follows:

Create Html

<input id="imageFile" name="imageFile" type="file" class="imageFile"  accept="image/*"   /> 
<input type="button" value="Resize Image"  onclick="ResizeImage()"/> 
<br/>
<img src="" id="preview"  >
<img src="" id="output">

Implement JavaScript Code For Resize Image

$(document).ready(function() {
    $('#imageFile').change(function(evt) {
        var files = evt.target.files;
        var file = files[0];
        if (file) {
            var reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('preview').src = e.target.result;
            };
            reader.readAsDataURL(file);
        }
    });
});
function ResizeImage() {
    if (window.File && window.FileReader && window.FileList && window.Blob) {
        var filesToUploads = document.getElementById('imageFile').files;
        var file = filesToUploads[0];
        if (file) {
            var reader = new FileReader();
            // Set the image once loaded into file reader
            reader.onload = function(e) {
                var img = document.createElement("img");
                img.src = e.target.result;
                var canvas = document.createElement("canvas");
                var ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0);
                var MAX_WIDTH = 400;
                var MAX_HEIGHT = 400;
                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);
                dataurl = canvas.toDataURL(file.type);
                document.getElementById('output').src = dataurl;
            }
            reader.readAsDataURL(file);
        }
    } else {
        alert('The File APIs are not fully supported in this browser.');
    }
}

Conclusion

javaScript resize image; In this tutorial, you have learned how to resize the image in javascript and how to convert the resize image into base64 content.

More JavaScript Tutorials

Leave a Comment