brunobar79 / J-I-C

J I C is a Javascript Image Compressor using HTML5 Canvas & File API that allows you to compress your jpeg & png images before uploading to the server (100% client-side and no extra libraries required!)
http://makeitsolutions.com/labs/jic/
MIT License
857 stars 196 forks source link

How to use with file input #49

Open sedestrian opened 7 years ago

sedestrian commented 7 years ago

Hi, i cannot figure out how to compress pictures chosen via the input type file, i tried creating a var = new Image() and setting its path to that of the image but it won't work. Please help

inotloh commented 7 years ago
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
    <script src="js/JIC.min.js" type="text/javascript"></script>
</head>
<body>
    <input type="file" id="input-image">
    <div>
        <p>Uploaded image</p>
        <img src="" id="source-image" width="200px">
    </div>
    <div>
        <p>Compressed image</p>
        <img src="" id="result-img" width="200px">
    </div>
    <script>
        var input_image = document.getElementById('input-image'),
            result_img = document.getElementById('result-img'),
            source_image = document.getElementById('source-image'),
            quality = 50,
            output_format = 'jpg';

        function readURL(input, source_image) {

            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function (e) {
                    source_image.src = e.target.result;
                };

                reader.readAsDataURL(input.files[0]);
            }
        }

        input_image.onchange = function (e) {
            readURL(this, source_image);
        };

        source_image.onload = function(){
            result_img.src = jic.compress(source_image, quality, output_format).src;
        }
    </script>
</body>
</html>
reyrestuff commented 7 years ago

Hi, I've adapted the above code to work by shrinking 4 different image uploads but each one is submitted as the full size image for some reason.

Please could someone explain how the original file that is chosen is then replaced by the compressed version. Each file chooser correctly creates a compressed version of the chosen file so I know that bits working/ It just doesn't seem to replace the original larger one as the one to be submitted

Thanks, Bob