0

Is there any builtin function in JavaScript to reduce the image size before uploading the image to server? I have the following code which uploads images and displays progress also. I am going to use it for webapp where a user clicks a photograph from a mobile camera. As the images from mobile cameras are too large, i need a function that can downsize the image to roughly 100x150 pixels. Javascript code:

var handleUpload = function(event){
event.preventDefault();
event.stopPropagation();

var fileInput = document.getElementById('file');

var data = new FormData();
data.append('stuimagebyajax',true); /*Flag to check in php so that we know file was uploaded through ajax*/ 
for(var i=0;i<=fileInput.files.length;++i)
    {
    data.append('file[]',fileInput.files[i]);
    }
var request = new XMLHttpRequest();
request.upload.addEventListener('progress',function(event){
    if(event.lengthComputable)
        {
        var percent = Math.round((event.loaded/event.total)*100);
        var progress =  document.getElementById('upload_progress'); 
        var bar = document.getElementById('uploadprogressbar');

        while(progress.hasChildNodes())
            {
            progress.removeChild(progress.firstChild);
            }
        progress.appendChild(document.createTextNode(percent + ' %'));
        bar.value = percent;
        }
    });
/*Load event is fired once the process is cimplete*/    
request.upload.addEventListener('load',function(event){
    document.getElementById('upload_progress').style.display = 'none';
    });

request.upload.addEventListener('error',function(event){
    document.getElementById('upload_progress').innerHTML = "Error uploading file!! Please Try Again.";
    });

request.addEventListener('readystatechange',function(event){
    if(this.readyState==4 && this.status==200)
        {
        console.log('Desired ready state reached');
        var links = document.getElementById('uploaded');
        var uploaded = eval(this.response);
        var div,i;
        for(var i=0;i<uploaded.length;++i)
            {
            console.log(i);
            div=document.createElement('div');
            a=document.createElement('a');
            a.setAttribute('href','stuuplds/'+uploaded[i]);
            a.appendChild(document.createTextNode(uploaded[i]));
            console.log('a is '+a);

            div.appendChild(a);

            links.appendChild(div);
            console.log('div is '+div);
            console.log('links is '+links);
            }
        console.log(this.response);
        }
    else
        {
        console.log('Server replied with HTTP status ' + this.status);
        }
    });

request.open("POST",'uploadprogressbartest.php');
request.setRequestHeader('Cache-Control','no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);
console.log(fileInput.files.length);
}

window.addEventListener('load',function(event){
var submit = document.getElementById('submit');
submit.addEventListener('click',handleUpload);
});

And here is the php code on server:

<?php
/*print_r($_FILES);*/

if(!empty($_FILES['file'])) /*Here 'file' is the name of array in input     type*/
 {
foreach($_FILES['file']['name'] as $key =>$name)
    {
    if($_FILES['file']['error'][$key]==0 && move_uploaded_file($_FILES['file']['tmp_name'][$key],"stuuplds/{$name}"))
        {
            $uploaded[]=$name;
        }
    }
}

if(!empty($_POST['stuimagebyajax']))
{
die(json_encode($uploaded));
}

/*print_r($uploaded);*/

?>

<!DOCTYPE html PUBLIC>
<html>
<head>
    <script type="text/javascript" src="upload.js"></script>
    <style type="text/css">
        #upload_progress {display:none;}
    </style>
    <title>File Upload</title>
</head>

<body>
    <div id="uploaded">
        <?php
        if(!empty($uploaded))
            {
            foreach($uploaded as $name)
                {
                    echo '<div><a href="stuuplds/' . $name . '">' . $name . '</a></div>';
                }
            }

        ?>


    </div>

    <div id="upload_progress"></div>
    <div>
    <form action="" method="post" enctype="multipart/form-data">
        <div>
            <input type="file" name="file[]" id="file" multiple="multiple" />
            <input type="submit" id="submit" value="Upload" />
            <progress id="uploadprogressbar" value="0" max="100"></progress>
        </div>
    </form>
    </div>
</body>

This effectively does the job of uploading files to a folder 'stuuplds' on the server while displaying progress while uploading. Now the only problem is how to reduce the image size to 100x150 pixels (roughly) before uploading. Can anyone please help.

For example, a typical image taken with a mid-range smartphone camera has a resolution of 4160x3120 pixels. But i only need 100x150 pixels image. So i dont need any kind of compression algorithm/function. What i am looking for is a javascript function that takes a large image taken from a smartphone camera (say 4160x3120 pixels) and downsizes it to 100x150 pixels so that the overall size-on-disc of the image is reduced significantly.

irshukhan
  • 169
  • 2
  • 2
  • 12

1 Answers1

0

You can utilize HTML5 canvas to resize images pre-uploading to server.

Proper answer is documented here

HTML5 Pre-resize images before uploading

Community
  • 1
  • 1
  • Thanks Shahzaib but i am having a hard time integrating that code with what i already have. I am new to Javascript and just know the bare bones. Although i do fully understand the underlying resizing algorithm in the code you pointed to, i am unable to understand where exactly to integrate it with the code i already have. I am already confused by so many methods provided at the given link and the code is 3 years old. Maybe things might have changed since then and maybe some simpler approach is available right now. Can anyone please help – irshukhan Jan 04 '16 at 19:25
  • Part of the difficulty is that you're trying to make modifications to a complex compressed image format (eg, JPG, PNG; of which you might need to handle all). There might be much easier methods of resizing on the server instead of using JavaScript, depending on which language you're using. – Katana314 Jan 04 '16 at 19:39
  • I know it seems daunting until you get hold of it... Best library for your use case is canvasResize, I have personally used it and works pretty well but as @Katana314 says it has its own problems specially with PNGs. https://github.com/gokercebeci/canvasResize – Shahzaib Ali Khan Jan 04 '16 at 19:44
  • Thank you for you help and support. Actually i have the code to reduce filesize on server-side in php but i wanted to do it on the client-side so that images upload faster. Images captured by modern smartphone cameras are of the order of megabytes which makes the upload process painful. But my project only needs to store almost thumbnail sized images in the database. So uploading a large image file and reducing the image size at server-side would waste both the data bandwidth as well as the time. – irshukhan Jan 05 '16 at 15:54
  • For example, a typical image taken with a mid-range smartphone camera has a resolution of 4160x3120 pixels. But i only need 100x150 pixels image. So i dont need any kind of compression algorithm/function. What i am looking for is a javascript function that takes a large image taken from a smartphone camera (say 4160x3120 pixels) and downsizes it to 100x150 pixels so that the overall size-on-disc of the image is reduced significantly. – irshukhan Jan 05 '16 at 15:59