Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs compress image before upload

I'm buliding a web site for mobile devices, that uses angular-file-upload.min.js for uploading images from a mobile device image library.

html code:

<div>
    <div class="rating-camera-icon">
        <input type="file" accept="image/*" name="file" ng-file-
         select="onFileSelect($files)">
    </div>
    <img ng-show="fileName" ng-src="server/{{fileName}}" width="40"
     style="margin-left:10px">
</div>

code:

$scope.onFileSelect = function($files) {
        for (var i = 0; i < $files.length; i++) {
            var file = $files[i];
            if (!file.type.match(/image.*/)) {
                // this file is not an image.
            };
            $scope.upload = $upload.upload({
                url: BASE_URL + 'upload.php',
                data: {myObj: $scope.myModelObj},
                file: file
            }).progress(function(evt) {
                    // console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
                    // $scope.fileProgress = evt.loaded / evt.total * 100.0;
                }).success(function(data, status, headers, config) {
                    // file is uploaded successfully
                    $scope.fileName = data;
                });
        }
    };

The upload is very slow in mobile devices. How can I compress the file?

like image 264
ben ezra Avatar asked Apr 23 '14 14:04

ben ezra


1 Answers

Stringifying the image into a base-64 text format is all fine and well, but it will take a small amount of time and certainly does not compress it. In fact it will likely be noticeably larger than the raw image. Unfortunately your browser will also not gzip an uploads. They can of course handle gzipped downloads. You could certainly try to do a gzip of the text itself using some pure JS solution. Looking on github you can find such things - https://github.com/beatgammit/gzip-js However, that will take some time as well and there is no guarantee that the compressed text version of the image is any smaller than the raw JPEG you attach.

A native mobile app might decide to use some native code JPEG or PNG optimization before sending (basically resample the image) if appropriate, but doing this out in JavaScript seems potentially problematic at this point in time. Given Atwood's law (of writing everything eventually in JavaScript) it certainly could be done but at this point in mid-2014 it isn't.

like image 75
TAP Avatar answered Oct 14 '22 07:10

TAP