Two html5 APIs, one file and one canvas, are used for compression. The file reads the file and then stores the compressed photos in the memory, finally, the img in the memory transfer form. src, followed by Form submission.
The photo was taken with a single SLR, with more than 5 MB of data. The three images under the ZIP file are more than 600 kb and more than 400 kb respectively. The last one of the kb images is of great distortion and the compression efficiency is quite high.
-
- File API Test
- <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
- <script type="text/javascript" src="js/JIC.js"></script>
- <script>
- function handleFileSelect (evt) {
- // var filebtn = document.getElementById(id);
- // console.log(filebtn);
- // var files = filebtn.target.files;
- // console.log(filebtn.target);
- // console.log(files);
- var files = evt.target.files;
- for (var i = 0, f; f = files[i]; i++) {
-
- // Only process image files.
- if (!f.type.match('image.*')) {
- continue;
- }
-
- var reader = new FileReader();
-
- // Closure to capture the file information.
- reader.onload = (function(theFile) {
- return function(e) {
- // Render thumbnail.
- // console.log(evt.target.files[0]);
- // console.log(e.target);
- console.log(e.target.result);
- var i = document.getElementById("test");
- i.src = event.target.result;
- console.log($(i).width());
- console.log($(i).height());
- $(i).css('width',$(i).width()/10+'px');
- //$(i).css('height',$(i).height()/10+'px');
- console.log($(i).width());
- console.log($(i).height());
- var quality = 50;
- i.src = jic.compress(i,quality).src;
- console.log(i.src);
- i.style.display = "block";
- };
- })(f);
-
- // Read in the image file as a data URL.
- reader.readAsDataURL(f);
- }
- }
-
- document.getElementById('fileImg').addEventListener('change', handleFileSelect, false);
- </script>
- Var jic = {
- /**
- * Es an Image Object (can be jpg or png) and returns a new Image Object compressed
- * @ Param {Image} source_img_obj The source Image Object
- * @ Param {Integer} quality The output quality of Image Object
- * @ Return {Image} result_image_obj The compressed Image Object
- */
-
- Compress: function (source_img_obj, quality, output_format ){
-
- Var mime_type = "image/jpeg ";
- If (output_format! = Undefined & output_format = "png "){
- Mime_type = "image/png ";
- }
-
-
- Var cvs = document. createElement ('canvas ');
- // NaturalWidth the width of the Real Image
- Cvs. width = source_img_obj.naturalWidth;
- Cvs. height = source_img_obj.naturalHeight;
- Var ctx = cvs. getContext ("2d"). drawImage (source_img_obj, 0, 0 );
- Var newImageData = cvs. toDataURL (mime_type, quality/100 );
- Var result_image_obj = new Image ();
- Result_image_obj.src = newImageData;
- Return result_image_obj;
- },
- Function ****(***){}
- }